I have working code that uploads an image to Amazon S3
Working code...
$filename = $s."/avatars/".$user_id."-".$file['name'];
$path_parts = pathinfo($file['name']);
$ext = $path_parts['extension'];
$input_file = S3::inputFile($file['tmp_name'], false);
if(S3::putObject($input_file, 'mybucket', $filename, S3::ACL_PUBLIC_READ)){
//Success handling
} else {
// Error handling
}
However, when I use GD to resize it, and try to upload it fails to work anymore.
Unworking code...
$size = getimagesize($file['tmp_name']);
$x = (int) $input['x'];
$y = (int) $input['y'];
$w = (int) $input['w'] ? $input['w'] : $size[0];
$h = (int) $input['h'] ? $input['h'] : $size[1];
$data = file_get_contents($file['tmp_name']);
$vImg = imagecreatefromstring($data);
$dstImg = imagecreatetruecolor($nw, $nh);
imagecopyresampled($dstImg, $vImg, 0, 0, $x, $y, $nw, $nh, $w, $h);
ob_start();
imagejpeg($dstImg, null, 100);
$jpeg = ob_get_contents();
ob_end_clean();
//Send to S3
$input = S3::inputFile($jpeg, false);
if(S3::putObject($input, 'mybucket', $filename, S3::ACL_PUBLIC_READ)){
// Success handling
} else {
// Error handling
}
Error message I receive is...
S3::inputFile(): Unable to open input file: ÿØÿà
Any ideas?? Am I getting the stream incorrectly?? Am I supposed to do something differently after resizing?? Do I even have to read the stream?? Or can I send the $dstImg resource??
Any help would be greatly appreciated
For anyone else having this problem.
I solved it like this
Changed this...
ob_start();
imagejpeg($dstImg, null, 100);
$jpeg_to_upload = ob_get_contents();
ob_end_clean();
To this...
$jpeg_to_upload = tempnam(sys_get_temp_dir(), "tempfilename");
imagejpeg($dstImg, $jpeg_to_upload);
Then sent it...
$input = S3::inputFile($jpeg_to_upload, false);
if(S3::putObject($input, 'mybucket', $filename, S3::ACL_PUBLIC_READ)){
Related
I want to rotate my crop image and then save. But its not working.
<?php
$newNamePrefix = $newname;
$manipulator = new ImageManipulator($_FILES['blogo']['tmp_name']);
$width = $manipulator->getWidth();
$height = $manipulator->getHeight();
$min= min($width ,$height);
$max= max($width ,$height);
$n=$min/800;
$d=$max/$n;
$newImage = $manipulator->resample($d,$d);
$newImage2 = $newImage->crop(0, 0, 800, 600);
// saving file to uploads folder
$manipulator->save('uploads/stores/'.$formData['url'] .'/'. $newNamePrefix.$fileExtension );
return $newname.$fileExtension;
?>
I tried this below code but it didn't work.
$degrees = 90;
$filename = $newImage2;
$source = imagecreatefromjpeg( $filename );
$rotate = imagerotate( $source, $degrees, 0 );
$fileName = 'uploads/stores/'.$formData['url'] .'/'. $newNamePrefix.$fileExtension;
// Output
imagejpeg( $rotate, $fileName, 100 );
If i use $filename = $_FILES['blogo']['tmp_name'] it works but if i use $filename = $newImage2; then it doesn't.
I am doing this first time so I have no idea whats the right way to do it.
It is because $_FILES['blogo']['tmp_name'] is a valid name whereas $newImage2 is not... Try to do something like:
echo $newImage2;
And you will understand what I mean.
hi i am retriving a base64 encoded version of image and i have to stored it by cropping it to small size. now i am not able to crop the image please help me
my Code is as follow..
Please help me in cropping base 64 image
$data = str_replace('data:image/png;base64,', '', $note['file']);
$data = str_replace(' ', '+', $data);
$decodedFile = base64_decode($data);
$file = fopen($destination , 'wb');
if(!fwrite($file, $decodedFile)){
//return("ERROR: can't save file to $destination");
return '-1';
}
fclose($file);
You can use the gd library for create the image file from binary code:
function binaryToFile($binary_imagen, $width, $height, $new_name, $url_destiny) {
try{
//actual size
$info = getimagesizefromstring($binary_imagen);
$old_width = $info[0];
$old_height = $info[1];
//new resource
$resource = imagecreatefromstring($binary_imagen);
$resource_copy = imagecreatetruecolor($width, $height);
imagealphablending( $resource_copy , false );
imagesavealpha( $resource_copy , true );
imagecopyresampled($resource_copy, $resource, 0, 0, 0, 0,
$width, $height,
$old_width, $old_height);
$url = $url_destiny."/".$new_name".png";
$final = imagepng($resource_copy, $url, 9);
imagedestroy($resource);
imagedestroy($resource_copy);
return 1;
}catch (Exception $e) {
return 0;
}
}
Not sure what your need but if it is some what like this you want to achieve then may be this will help you
PHP crop image from base64_decode
I'm trying to hit a php page from a node server so that it will generate some thumbnail images. The problem is that it isn't generating the images when i hit do a jquery.get request from node. It works perfectly if I hit the page from a browser, though.
Here is the php code:
<?php
$thumbsFolder = 'output/thumbs/';
$mediumFolder = 'output/medium/';
$originals = glob("output/*.jpg");
$thumbs = glob("output/thumbs/*.jpg");
// only process the images that are missing
$diff = array_diff($originals, $thumbs);
foreach ($diff as $file) {
processImage($file, $thumbsFolder, 150);
processImage($file, $mediumFolder, 600);
}
function processImage($imagePath, $outputFolder, $targetWidth){
$imageSize = getimagesize($imagePath);
$originalWidth = $imageSize[0];
$originalHeight = $imageSize[1];
$targetHeight = round($originalHeight * $targetWidth / $originalWidth);
$urlElements = explode("/", $imagePath);
$fileName = array_pop($urlElements);
$fileName = explode(".", $fileName);
$ext = array_pop($fileName);
$newFilePath = $outputFolder.join($fileName, "").".".$ext;
$im = imagecreatefromjpeg($imagePath);
$sm = imagecreatetruecolor($targetWidth, $targetHeight);
imagealphablending($sm, false);
imagecopyresampled($sm, $im, 0, 0, 0, 0, $targetWidth, $targetHeight, $originalWidth, $originalHeight);
imagejpeg($sm, $newFilePath, 75);
}
?>
Here is the node script that hits the endpoint.
$.get("http://absolutepath.com/pi-lapse/thumb-gen.php", function(e){console.log(e)})
I also tried curl, and it didn't work.
I am working in PHP and trying to use iMagick library to do an image conversion from SVG to JPG using shell_exec command. All seems to work, but the output JPG comes out very distorted. I almost get a feeling that the image is first converted and then resized.
I tried using "resize" and "scale" with same results.
Here is the command:
"-resize 800x800 -quality 95 image.svg image.jpg"
Any insights? Thanks in advance.
For anyone looking for a solution to this. Someone was able to come up with the following hack (with some of my edits):
createThumbnail("input.svg", "output.jpg", 500, 500, $cdn_container);
function createThumbnail($filename, $thname, $width=100, $height=100, $cdn=null)
{
try {
$extension = substr($filename, (strrpos($filename, '.')) + 1 - strlen($filename));
$fallback_save_path = "images/designs";
if ($extension == "svg") {
$im = new Imagick();
$svgdata = file_get_contents($filename);
$svgdata = svgScaleHack($svgdata, $width, $height);
//$im->setBackgroundColor(new ImagickPixel('transparent'));
$im->readImageBlob($svgdata);
$im->setImageFormat("jpg");
$im->resizeImage($width, $height, imagick::FILTER_LANCZOS, 1);
$raw_data = $im->getImageBlob();
(is_null($cdn)) ? file_put_contents($fallback_save_path . '/' . $thname, $im->getImageBlob()) : '';
} else if ($extension == "jpg") {
$im = new Imagick($filename);
$im->stripImage();
// Save as progressive JPEG
$im->setInterlaceScheme(Imagick::INTERLACE_PLANE);
$raw_data = $im->resizeImage($width, $height, imagick::FILTER_LANCZOS, 1);
// Set quality
// $im->setImageCompressionQuality(85);
(is_null($cdn)) ? $im->writeImage($fallback_save_path . '/' . $thname) : '';
}
if (!is_null($cdn)) {
$imageObject = $cdn->DataObject();
$imageObject->SetData( $raw_data );
$imageObject->name = $thname;
$imageObject->content_type = 'image/jpg';
$imageObject->Create();
}
$im->clear();
$im->destroy();
return true;
}
catch(Exception $e) {
return false;
}
}
function svgScaleHack($svg, $minWidth, $minHeight)
{
$reW = '/(.*<svg[^>]* width=")([\d.]+px)(.*)/si';
$reH = '/(.*<svg[^>]* height=")([\d.]+px)(.*)/si';
preg_match($reW, $svg, $mw);
preg_match($reH, $svg, $mh);
$width = floatval($mw[2]);
$height = floatval($mh[2]);
if (!$width || !$height) return false;
// scale to make width and height big enough
$scale = 1;
if ($width < $minWidth)
$scale = $minWidth/$width;
if ($height < $minHeight)
$scale = max($scale, ($minHeight/$height));
$width *= $scale*2;
$height *= $scale*2;
$svg = preg_replace($reW, "\${1}{$width}px\${3}", $svg);
$svg = preg_replace($reH, "\${1}{$height}px\${3}", $svg);
return $svg;
}
In my php script in am trying to get an image from a URL, resize it, and upload it to my server. The script can be seen at http://getsharp.net/imageupload.php?admin=rene - The script is seen below (there is of course also some other PHP and HTML in it, but this is the part giving me an issue):
$admin = $_REQUEST['admin'];
$url = $_POST['uploadlink'];
if ($_POST['filename']){
$filename = $_POST['filename'].".jpg";
} else {
$urlinfo = parse_url($url);
$filename = basename($urlinfo['path']);
$filenamearray = explode(".", $filename);
$filenamebase = $filenamearray[0];
$filenamebase = substr($filenamebase, 0, 20); // max 20 characters
$filename = $filenamebase.".jpg";
}
// Get new dimensions
list($width, $height) = getimagesize($url);
$new_width = 300;
$ratio = $height/$width;
$new_height = 300*$ratio;
// Resample
$image_p = imagecreatetruecolor($new_width, $new_height);
if(exif_imagetype($url) == IMAGETYPE_GIF){
$image = imagecreatefromgif($url);
}else if(exif_imagetype($url) == IMAGETYPE_JPEG){
$image = imagecreatefromjpeg($url);
}else if(exif_imagetype($url) == IMAGETYPE_PNG){
$image = imagecreatefrompng($url);
}else{
$image = false;
}
imagecopyresampled($image_p, $image, 0, 0, 0, 0, $new_width, $new_height, $width, $height);
if(is_dir("images/upload/".$admin."/")){
// Output
imagejpeg($image_p, "images/upload/".$admin."/".$filename);
imagedestroy($image_p);
}else{
mkdir("images/upload/".$admin."/");
// Output
imagejpeg($image_p, "images/upload/".$admin."/".$filename);
imagedestroy($image_p);
}
$URL="http://getsharp.net/imageupload.php?admin=".$admin;
header ("Location: $URL");
Everything is working fine, except that when I throw in a new URL it gives me the following error: Warning: getimagesize(http://buffalocomputerconsulting.com/images/computer.jpg): failed to open stream: Connection timed out in.
However, if i throw in the exact same URL right after, there is no problem, and the image is being uploaded. So every time I try a new URL the first time, it gives me the above error. How can this be?
Thanks.
Your DNS resolves too slowly
Your server tries a nonreplying DNS first
Your server tries to connect on IPv6 first
Your uplink is slow as molasses but it has a caching proxy
I am sure there are more. Try your script on another machine and see whether it changes.