I am trying to simply get a test image, crop it a bit, and display it. The thing is, I am doing this from PHP, and every attempt I have made thus far has frustrated me even more; /* and the internet is telling me to do things that I have already done. */
OK, so what have you done??
I have tried various ways of getting the $image itself. I have tried the following:
Using imagecreatefromstring($url); /* where $url is the location of the image (I am pulling from random sites, which is a necessity for my project */
Using imagecreatefromstring(file_get_contents($url)); and then, in a <div> tag, echoing the image
Using imagecreatefromstring(file_get_contents($url)); and then, in an <img> tag, echoing the image
Doing 3., except using imagejpeg($image)
Doing 4., except, this time, putting header('Content-Type: image/jpeg');
OK, what happened?
First attempt returned a nice error saying that $image was not recognized.
Second attempt seems to work, but instead of an image, I get back the following text: Resource id #5
Third attempt gives me a bunch of gibberish.
Fourth attempt also gave me a bunch of gibberish.
Fifth attempt gave me a black screen with this error message: The image “http://localhost/ResearchProject/sampleImageDisplay.php” cannot be displayed because it contains errors.
Here is the final code (and header.php just contains all of the necessary HTML tags to display the web page (the DOCTYPE tag, the html tag, the meta tag...) ):
<?php
include "header.php";
$url = "http://byebyedoctor.com/wp-content/uploads/2010/12/alopecia-areata-3.jpg";
$image = imagecreatefromstring(file_get_contents($url));
?>
<img>
<?php header('Content-Type: image/jpeg'); imagejpeg($image); ?>
</img>
<?php imagedestroy($image); ?>
</body>
</html>
Why can't I display this simple image??
This code worked for me. Just create empty php file and paste this code. It should return the photo of a semi-bold man.
$url = "http://byebyedoctor.com/wp-content/uploads/2010/12/alopecia-areata-3.jpg";
$im = imagecreatefromstring(file_get_contents($url));
if ($im !== false) {
header('Content-Type: image/png');
imagepng($im);
imagedestroy($im);
}
else {
echo 'An error occurred.';
}
First off...
You have to make sure that "allow_url_fopen" is enabled in php.ini.
If you have access to this file just change
;allow_url_fopen
To
allow_url_fopen
Some hosts disable access to php.ini though.
Then all you have to do is this....
$url = "http://byebyedoctor.com/wp-content/uploads/2010/12/alopecia-areata-3.jpg";
$image = file_get_contents($url);
Then you can store it temporarily to resize it or whatever...
//Store in the filesystem.
$fp = fopen("/location/to/save/tempimage.jpg", "w");
fwrite($fp, $image);
fclose($fp);
Your major planning problem is: You try to include you image into a html code.
For this you need 2 phps:
A php file what contains your html-code with an img-tag (src must be the second php-file)
A php file what reads you base image and outputs the BINARY image data
your_htmlpage.php
<html>
<?php
include "header.php";
?>
<body>
<img src="your_image.php">
</body>
</html>
your_image.php
<?php
$url = "http://byebyedoctor.com/wp-content/uploads/2010/12/alopecia-areata-3.jpg";
$image = imagecreatefromstring(file_get_contents($url));
if($image !== false) {
header('Content-Type: image/jpeg');
imagejpeg($image);
imagedestroy($image);
} else {
header("X-Error", true, 404);
echo "Error loading remote image";
}
?>
Another option would be to send the image as base64encoded String to the browser. But this means that the WHOLE image-data is part of the html-code.
e.g. lik this:
<html>
<?php
include "header.php";
$url = "http://byebyedoctor.com/wp-content/uploads/2010/12/alopecia-areata-3.jpg";
$image = imagecreatefromstring(file_get_contents($url));
if($image !== false) {
// start buffering and catch image output
ob_start();
imagejpg($image);
$contents = ob_get_contents();
ob_end_clean();
imagedestroy($image);
$img_data = "data:image/jpg;base64,".base64_encode($contents);
} else {
$img_data = "";
}
?>
<body>
<img src="<?php echo $img_data; ?>">
</body>
</html>
Related
The code I have should output a jpg from a list of files in a directory however it is not. I have trawled this site and tried different methods but not helped. I am a relative beginner at php so looking for any help at all.
I have tried using img src in the php code but I am trying to get the image to display within a Wordpress post so I cannot echo the img src within the script. I have tried file_get_contents and read file as well but it may be my lack of knowledge holding me back.
<?php
$imagepath = htmlspecialchars($_GET["image"]);
$imagenum = htmlspecialchars($_GET["num"]);
define('LOCALHOST', 'localhost' === $_SERVER['SERVER_NAME'] );
If(LOCALHOST){
define('PATH_IMAGES', 'this_path');
}else{
define('PATH_IMAGES', '../../../Images/');
}
$arrnum = $GLOBALS[imagenum] - 1;
$dirname = PATH_IMAGES . $GLOBALS[imagepath]."/";
$images = scandir($dirname);
rsort($images);
$ignore = Array(".", "..");
foreach($images as $curimg){
if(!in_array($curimg, $ignore)) {
header('Content-type: image/jpeg');
file_get_contents('$dirname$images[$arrnum]');
}
}
?>
Have you tried readfile(...); should read and output the file. In your example you are not outputting the image data
http://php.net/manual/en/function.readfile.php
Im trying to display images from backend of my app
<?php foreach ($img as $key=>$row): ?>
<div class="products_inside_wrapper intro_wrapper">
<div class="classes_inside_item bordered_wht_border">
<?php
foreach (explode(';',rtrim($row['images'],';')) as $key_img => $value_img)
{
?>
<?php echo Html::img('#backend/web'.'/'.$value_img);?>
<?php
}
?>
</div>
</div>
<?php endforeach; ?>
Tried with above code to display all images, but getting error Not allowed to load local resource when I open Google Chrome Inspect Element
i think you are using a local url instead of using this
<?php echo Html::img('#backend/web'.'/'.$value_img);?>
try using it like
<?= Html::img(Yii::getAlias('#web').'/images/'.$value_img]);?>
As stig-js answered you can't load local saved image directly, If you're really interested into loading resources from a local path, you can open image as a binary file with fopen and echo the content of it with a proper header to output. In general way, you can add a method to your model like this:
public function getImage($imageName)
{
$imagePath = '#backend/web' . '/' . $imageName;
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$contentType = finfo_file($fileInfo, $imagePath);
finfo_close($fileInfo);
$fp = fopen($imagePath, 'r');
header("Content-Type: " . $contentType);
header("Content-Length: " . filesize($imagePath));
ob_end_clean();
fpassthru($fp);
}
P.S: Also you can use combination of this answer with showing image as base64 on HTML. See How to display Base64 images in HTML?
Images must be accesible by an url, like
yoursite.com/backend/imagedir/IMG'
If yoursite.com/backend points to your backend/web folder.
Backend alias points to your local path, so you need a custom alias to reach image folders.
Yii2 aliases: http://www.yiiframework.com/doc-2.0/guide-concept-aliases.html
I'm still learning a lot of terminology with php, so I find it hard to find some answer in similar questions. I'm looking to print a custom url into a PHP statement so I can print the contents of an .svg file. I'm using drupal 7.
Below are some examples of what I have tried but the files url keeps being printed?
<?php echo file_get_contents("print $fields['field_svg']->content"); ?>
or
<?php $file=print $fields['field_svg']->content ?>
<?php echo file_get_contents("echo $file"); ?>
or
$image = file_get_contents($path);
$destination = $fields['field_svg']->content;
$file = file_save_data($image, $destination, FILE_EXISTS_REPLACE);
if (is_object($file)) {
$file->status = 1;
$file = file_save($file);
}
Thanks
I want a PHP to be able to send 1 of 3 images, depending on a $_GET[] parameter. I have the images as three separate PNGs right now, and would like the PHP script to have those embedded in it, then return the specified image. So, I want one PHP script instead of 3 images. Is this possible? I don't need to create special images on the fly, just print out one of those. Thanks!
If your images are in files, use PHP's readfile() function, and send a content-type header before outputting it:
<?php
$imagePaths = array(
'1' => 'file1.png',
'2' => 'file2.png',
'3' => 'file3.png',
);
$type = $_GET['img'];
if ( isset($imagePaths[$type]) ) {
$imagePath = $imagePaths[$type];
header('Content-Type: image/png');
readfile($imagePath);
} else {
header('HTTP/1.1 404 File Not Found');
echo 'File not found.';
}
?>
EDIT:
You could also embed your images in the script by encoding them e.g. as Base64, then embed them as strings in PHP, then decode it there with base64_decode to deliver them:
<?php
$imageData = array(
'1' => '...', // Base64-encoded data as string
...
);
$type = $_GET['img'];
if ( isset($imageData[$type]) ) {
header('Content-Type: image/png');
echo base64_decode($imageData[$type]);
} else {
header('HTTP/1.1 404 File Not Found');
echo 'File not found.';
}
?>
You could also use PHP to encode the image on the command line. Just execute this PHP script in the command line (php script.php image1.png image2.png image3.png > output.php) and save its output, and incorporate it into your script:
<?php
$imageData = array();
foreach ($argv as $index => $imagePath)
$imageData[(string)($index + 1)] = base64_encode(file_get_contents($imagePath));
echo '$imageData = '.var_export($imageData, true).';';
?>
I have not tested the following, but it should work. Use this script to get PHP code that will contain the image data.
To get the image:
$image = base64_encode(file_get_contents("image.png"));
// The string $image now contains your image data.
Get this (potentially big) string in your code where you want the image, for each image. Print it and copy it then paste it. Import it as a text file over the web. That's up to you.
Then, to print the image (only the image as if the PHP script were the image), do:
header("content-type: image/png");
print base64_decode($image);
Of course, you would put each image data in an array or something like that.
Let me know if it works.
Yes, it's possible.
Do this:
Write a php script deciding which image to output.
Set the appropriate headers with header() function (I.e. Content-type)
Open the file, read it and send it to the output stream.
Remember that you will probably lose any benefits from browser's cache with this approach...
A fast but not really secure nor elegant way to do it...
<?php
switch($_GET['type']){
case "1":
$image = "image1.png";
break;
case "2":
$image = "image2.png";
break;
case "3":
$image = "image3.png";
break;
}
header('Content-Type: image/png');
readfile($image);
?>
the moral of the story: use header() and readfile() =D
I want to load image via c:/user_name/image/image_name.jpg using http://intranet/user/index.php.
<img src="file:///c:/user_name/image/image_name.jpg">
How do I display them?
Thanks
Jean
You realize this would only work if that image is in the exact same location on every machine which will be viewing this page? Is there any reason you can't serve up the image normally, via the web server itself?
Since you're using an absolute Windows path, this would only work on Windows machines, which actually have a C drive, the same directories, etc... It won't work at all on a Mac or Linux or whatever else box, since they don't bother with drive letters.
followup:
after pondering your question a bit, it looks like you want to serve up a specific image that's not stored in your document root and serve it from a specific page. If you put something like this at the start of your index.php:
<?php
if (isset($_GET['username']) && isset($_GET['image'])) {
$user = $_GET['username'];
$image = $_GET['image'];
$path = "C:\\{$user}\\image\\{$image}";
if (is_readable($path)) {
$info = getimagesize($path);
if ($info !== FALSE) {
header("Content-type: {$info['mime']}");
readfile($path);
exit();
}
}
}
?>
and within the HTML:
<img src="index.php?user=user_name&image=image_name" />
Of course, this is very basic, and serving up files this way is highly insecure, but most likely this is the basics of what you wanted.
<?php
$path = "C:\\xampp\\htdocs\\Create.jpg";
if (is_readable($path))
{
$info = getimagesize($path);
if ($info !== FALSE)
{
header("Content-type: {$info['mime']}");
readfile($path);
echo '<img src="data:image/jpeg;base64,'. base64_encode($path) .'" height="100" width="100"/>';
}
}
?>