Show images from temp directory to end users
I am using the image rotation feature. I rotate the image and save it to tmp directory using
$rotate = imagerotate($source, 90, 0);
$rotatedTmpFile = tempnam('/tmp', 'rotatedThumbnailImage');
imagejpeg($rotate, $rotatedTmpFile ,100);
The files are created in the tmp folder. But now I want
- read the contents of the tmp directory
- Generate url of tmp image file
- Send this src request in response to the ajax call
JavaScript:
$.ajax({
url: PAdmin.roateImageUrl,
data: {
mediaId: id[1],
src: src
},
type: 'POST',
success: function(response) {
img.attr('src', response);
}
});
- Show this rotated image to the end user before uploading to the S3 server.
Please, help.
source to share
I'm pretty sure / tmp is not directly accessible through your webserver. You must either navigate from / tmp to a directory in your docroot, or alternatively, directly encode the image in html; using
$mime = mime_content_type($rotatedTmpFile);
$data = file_get_contents($rotatedTmpFile);
exit('data:' . $mime . ';base64,' . base64_encode($data));
this should work like image-src, but can be a somewhat expensive resource
source to share
Got a solution with @Sjon.
$.ajax({
url: PAdmin.roateImageUrl,
data: {mediaId:id[1],src: src},
type: 'POST',
success:
function(response){
img.attr('src',response);
}
});
In PAdmin.roateImageUrl:
Note. The exception was not handled in this code.
$rotate = imagerotate($source, 90, 0);
$rotatedTmpFile = tempnam('/tmp', 'rotatedThumbnailImage');
imagejpeg($rotate, $rotatedTmpFile ,100);
list($imageWidth, $imageHeight, $imageType) = getimagesize($rotatedTmpFile);
$type = image_type_to_mime_type($imageType);
$data = file_get_contents($rotatedTmpFile);
echo 'data:image/' . $type . ';base64,' . base64_encode($data);
exit;
source to share
Typically, you use a function move_uploaded_file()
to move the rotated image to some "temporary" accessible folder on the Internet (for example, " images/temp/
").
You will generate a random name for the image (if required for security reasons) and you can easily get the URL simply by adding the filename to " /images/temp/
".
source to share