I want to return an image over an URL like http://placehold.it/500x500.
I have my URL http://example.inc/assets/image/35345, which calls an action on controller. The controller get some data (name, id, etc.) from database and also a binary string of the image content.
On the frontend site, i have my img tag, where i want to call the url in my src attribute.
<img src="http://example.inc/assets/image/35345">
Some more information, i use slim PHP Framework and my server is an ubuntu 13.x system (vagrant etc.). I am an typically frontend developer and dont have good skills # PHP.
Following snippets works:
$file = fopen($name, 'wb');
fwrite($file, $binaryData);
fclose($file);
but I dont want to generate files in a directory. Is this possible?
EDIT: Content-Type and Content-Length Headers are set, that is not the problem.
Grab the contents of the image, base_64 encode it, then return a a base64 image.
$file = file_get_contents($name);
list($width, $height, $type, $attr) = getimagesize($file);
echo '<img src="data:image/'.$type.';'.base64_encode($file).'"/>';
You should upload images in directory by using something like this. This code will upload your image in directory.
if ($_FILES['file']['name'] != "") {
$filename = $_FILES['file']['name']; //getting name of the file from form
$filesize = $_FILES['file']['size'];
$info = new SplFileInfo($filename);
$ext = $info->getExtension();
$filesize1 = ($filesize * .0009765625) * .0009765625;
if (!($ext == 'jpg' || $ext == 'png' || $ext == 'jpeg')) {
//set some error message and redirect
}
if ($filesize1 >= 5.0) {
//set message image size should be less than 5 mb
}
$target_path = $_SERVER['DOCUMENT_ROOT'] . "../images/profile_images/";
move_uploaded_file($_FILES['file']['tmp_name'], "$target_path" . $_FILES['file']['name']) or
die("Could not copy file!");
}
Insert image name(with extension) in database.($filename here)
Fetch image name from database and store in variable($profile_image here),use it in img src.
<a href='../images/profile_images/$profile_image'><img alt='Avatar' src='../images/profile_images/$profile_image'></a>
You can use only Anchor tag to redirect user on image in another tab in browser.
hope this answer will help you.
Because i had an mssql database with iso charset i have converted all of my results to utf-8, the problem was, that the bytestring also converted to utf-8.
after non converting the bytestring i also returned the bytestring and set the header content type to image/extension
Related
I am loading an image from a remote server (google for example), but PHP never treats it as an image. This is my code:
$photo = imagecreatefromstring(file_get_contents("https://some.com/image.jpg"));
$filename = $photo["name"];
$ext = strtolower(pathinfo($filename, PATHINFO_EXTENSION)); //returns ""
$filepath = $photo["tmp_name"];
is_array(getimagesize($filepath); //returns false
What am I doing wrong?
imagecreatefromstring returns an image not array.
$photo = imagecreatefromstring(file_get_contents("https://some.com/image.jpg"));
ob_end_clean();
header('Content-type: image/jpeg');
imagejpeg($photo, null, 80);
If this code doesn't produce an image then start debugging from finding out the return value of file_get_contents().
Also - after creating an image (using any of imagecreatefrom... functions) you are dealing with image resource, not file system or any other object. Image resource does not have information you are trying to extract (name, pathinfo etc.)
I have a PHP script that, if a user-uploaded image file isn't a .png image, it will use Imagemagick to convert it to .png before saving it to a server. However it can only use the .tmp file from the HTML form, so it has to convert the CONTENTS while keeping the .tmp (and its filename) intact. This is my code so far:
if (exif_imagetype($tmpName) != IMAGETYPE_PNG) {
$uploadOk = 0; // don't upload later
$im = new Imagick("$tmpName");
$im->setImageFormat( "png" );
file_put_contents($tmpName, '');
file_put_contents(file_get_contents($im), $tmpName);
if (exif_imagetype($tmpName) != IMAGETYPE_PNG) { //check again
// try again or throw error somehow?
} else {
$uploadOk = 1;
}
} else {
$uploadOk = 1;
}
How do I properly use Imagick to convert the contents of my temp file into a png version of the original (non png) image?
EDIT: It could also be that the script should work fine, and the problem is something entirely different. Not sure at this point.
if you are to use, IMAGICK library, then you can use something like this:
...need to explain how you get the .tmp file, which I guess by using a form on your site... so...
.. get the post file
// This equals to 'some/server/path/temp/filename.tmp'
$original_image = $_FILE['tmp_name'];
// Lets work on the Imagick...
$img = new Imagick($original_image);
$img->setImageBackgroundColor('white');// red, black..etc
$img = $img->flattenImages(); // Use this instead.
$img->setImageFormat('png');
$new_image_name = 'nice_image_name.png';
$img->writeImage($new_image_name);
See if that works for you...
I'm stuck with a little problem and can't find a solution. I'm outputting my images to the website as base64 data URI. If someone opens the image directly in the browser the url to the image would be the data URI which works find but the name that shows in the browser tab is something random and i want to change that. I know that i could add /new+name++that+i+want at the end of the data URI to change the title that shows in the browser but sometimes there is already a name/title at the end of the data URI and in this case it would just create an error if I add something to the end. Is there any save way to set a title/name rather than adding something at the end and hoping it doesn't create an error?
Thanks for reading and have a nice day.
My Code:
$img = "uploads/images/smile.png";
$filetype = mime_content_type($img);
$imgdata = base64_encode(file_get_contents($img));
$src = "data:" . $filetype . ";base64," . $imgdata;
Use pathinfo for file type $filetype = pathinfo($path, PATHINFO_EXTENSION);
$img = "uploads/images/smile.png";
$filetype = pathinfo($img, PATHINFO_EXTENSION);
$imgdata = base64_encode(file_get_contents($img));
$src = "data:" . $filetype . ";base64," . $imgdata;
Stuck on this one. I have this function below that simply takes $ImageSrc which is an external image from anywhere, eg imgur, and then saves it locally (this is not a scraper, I'm allowing people to attach images to their profiles)
public function UploadScreenshot($ImageSrc, $Title, $Description = false) {
$RandomName = substr(md5($Title . time()), 0, 20);
$UploadDir = "/home/vanrust/public_html/Screenshots/";
$file = pathinfo($ImageSrc);
$ext = $file["extension"];
if (!in_array($ext, array('jpg','png','bmp','jpeg'))) return array("error" => "Invalid File Type");
$RandomName = "{$RandomName}.{$ext}";
$image = file_get_contents($ImageSrc);
file_put_contents($UploadDir . $RandomName, $image);
}
The result of the file no matter what is unrecognizable.
The image:
After UploadScreenshot() has retrieved it:
Try to use rename() to move the original file to the new location and rename it.
$file = pathinfo($ImageSrc);
$ext = $file["extension"];
if (!in_array($ext, array('jpg','png','bmp','jpeg'))) return array("error" => "Invalid File Type");
$RandomName = "{$RandomName}.{$ext}";
rename($UploadDir . $RandomName, $ImageSrc);
}
Alternatively, you can use move_uploaded_file() if your $ImageSrc does contain a valid upload file (meaning that it was uploaded via PHP's HTTP POST upload mechanism).
file_put_contents() needs to be used with caution. A single offset (in binary codes) at the beginning or at the end of the file will significantly alter the picture. It requires a validation at the end to compare both files bytes.
I'm saving some of my image in to mysql database using base64_encode.
now I want to restore them back to file system.
How can I do that?
Edit...!
Ok, I did not explain enough.
I use this code to encode my image and save them in to a blob table:
function base64_encode_image ($imagefile) {
$imgtype = array('jpg', 'gif', 'png');
$filename = file_exists($imagefile) ? htmlentities($imagefile) : die('Image file name does not exist');
$filetype = pathinfo($filename, PATHINFO_EXTENSION);
if (in_array($filetype, $imgtype)){
$imgbinary = fread(fopen($filename, "r"), filesize($filename));
} else {
die ('Invalid image type, jpg, gif, and png is only allowed');
}
return 'data:image/' . $filetype . ';base64,' . base64_encode($imgbinary);
}
and use this code to show my image in browser:
if (!isset($_GET['id']) && !ctype_digit($_GET['id'])){
die('Error');
} else {
require_once( addslashes(dirname(dirname(__FILE__)) . '/config.php') );
require_once( addslashes(dirname(__FILE__) . '/Functions.php'));
$row = mysql_fetch_array(mysql_query ("SELECT `id`,`cover_small` FROM `om_manga` WHERE `Active` = '1' AND `id` = '".sql_quote($_GET['id'])."'"));
if (isset($row['id'])){
header("Content-type: image/jpeg");
readfile($row['cover_small']);
} else {
die('Error');
}
}
Now i want them back to a jpg file.
The size of all those image are less then 3kb.
Use PHP's base64_decode() function to convert the encoded data back to binary.
Since base64_decode returns a string, you can use file_put_contents() to write the decoded contents to a file.
It makes me wonder why you're storing the image base64 encoded if you're not using it in that format. You could just as easily store the image in binary format in a binary blob column.
Base64 encoding adds a 33% character overhead (not bytes).
Edit for revised question
The answer to your second question is subjective without context. Without knowing the details of your system, I can't recommend whether you should extract the images.
Decode it the same way you encoded it...
base64_decode()
You might want to store the file extension of the image when writing it to the database so that you can restore it accurately. Just concatenate the new name with the existing extension.
What you should so is something similar to this :
// Retrieved values from database
$encodedImg = $sqlResult['encoded_img'];
$ext = $sqlResult['encoded_img_ext'];
// Concatenate new file name with existing extention
// NOTE : This parameter is a full path. Make sure that the folder
// you are writing the file to has the correct permissions allowing the
// script write access.
$newImagePath = "/some/path/on/the/servers/filesystem/";
$newImageName = $newImagePath."decoded_image.".$ext;
// Saving the decoded file with the new file name.
file_put_contents($newImageName, base64_decode($encodedImg));