convert image 64X64 px after decoding base64 image in php - php

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

Related

image not uploading properly when uploading from ios device camera in php

I am creating a project in codeigniter in which user can upload his profile image. I am using image library to upload it. When I am uploading image using camera in IOS device, image uploaded with some greyed out area. Code in library is
function createImage($iMageName,$folderName){
$width = 500; $height = true;
$data=base64_decode($iMageName);
$f = finfo_open();
$mime_type = finfo_buffer($f, $data, FILEINFO_MIME_TYPE);
$image = imagecreatefromstring($data);
$height = $height === true ? (ImageSY($image) * $width / ImageSX($image)) : $height;
$output = ImageCreateTrueColor($width, $height);
$imgThumb=uniqid().strtotime(date("Y-m-d H:i:s")).'.jpg';
$imageName=$folderName.$imgThumb;
$fullpath=FCPATH.$imageName;
ImageCopyResampled($output, $image, 0, 0, 0, 0, $width, $height, ImageSX($image), ImageSY($image));
imagejpeg($output, $fullpath, 90);
return $imageName;
}
Working fine for web and android device but problem in ios device, see uploaded image
I have also face the same issue.
Problem will occurs in following condition:
file size. Please validate the file size.
Please write the below code and check that it's working.
function createImage($iMageName,$folderName){
ini_set ('gd.jpeg_ignore_warning', 1);
$width = 500; $height = true;
$data=base64_decode($iMageName);
$f = finfo_open();
$mime_type = finfo_buffer($f, $data, FILEINFO_MIME_TYPE);
$image = #imagecreatefromstring($data);
$height = $height === true ? (ImageSY($image) * $width /
ImageSX($image)) : $height;
$output = #ImageCreateTrueColor($width, $height);
$imgThumb=uniqid().strtotime(date("Y-m-d H:i:s")).'.jpg';
$imageName=$folderName.$imgThumb;
$fullpath=FCPATH.$imageName;
#ImageCopyResampled($output, $image, 0, 0, 0, 0, $width,
$height, ImageSX($image), ImageSY($image));
imagejpeg($output, $fullpath, 90);
return $imageName;
}
Thanks , This will helpfull for you

Image file size smaller form base64 encode

There is tow image in base64 format ($theme_image_enc and $theme_image_enc_little). Now I want to make the second image ($theme_image_enc_little) size smaller like 15kb. How can do that?
$image = ($_FILES["my_image"]["name"]);
$theme_image = ($_FILES["my_image"]["tmp_name"]);
$bin_string = file_get_contents("$theme_image");
$theme_image_enc = base64_encode($bin_string);
$WIDTH = 400; // The size of your new image
$HEIGHT = 300; // The size of your new image
$QUALITY = 100; //The quality of your new image
$org_w = 850;
$org_h = 660;
$theme_image_little = imagecreatefromstring(base64_decode($theme_image_enc));
$image_little = imagecreatetruecolor($WIDTH, $HEIGHT);
imagecopyresampled($image_little, $theme_image_little, 0, 0, 0, 0, $WIDTH, $HEIGHT, $org_w, $org_h);
ob_start();
imagepng($image_little);
$contents = ob_get_contents();
ob_end_clean();
echo $theme_image_enc_little = base64_encode($contents);
try to show low image size in the browser you need to reduce the quality using with imagejpeg function
// Take value between $quality = (0 < 100)
imagejpeg($theme_image_enc_little, NULL, $quality);

PHP Imagick black areas after converting PDF to JPG

I'm using Imagick to generate JPG thumbnails for PDFs files but some of them generate with black areas (http://i.imgur.com/fKBncKw.jpg) – I'm assuming it's caused by transparency in the PDFs but can anything be done about it?
Code I'm using to generate these:
$imagick = new Imagick($filename);
$imagick->setIteratorIndex(0);
$imagick->setImageFormat('jpg');
return $imagick->getImageBlob();
Is there a way to flatten the PDF and/or add a white background so that the black areas don't appear?
Here is a solution which will only work for PNG to JPG.
This code adds a white background to the transparent areas in PNG and converts it to JPG.
What it does?
This code takes all PNG images from a folder, converts them to JPG's with white backgrounds and saves them in another folder.
<?php
ini_set('max_execution_time', 3000);
$dir = 'transparent/';
$arr = scandir($dir);
for($i=0;$i<count($arr);$i++)
{
if($i==0 || $i==1)
{
}
else{
$input_file = "transparent/".$arr[$i];
$output_file = "White/".str_replace('.png','.jpg',$arr[$i]);
$input = imagecreatefrompng($input_file);
list($width, $height) = getimagesize($input_file);
$output = imagecreatetruecolor($width, $height);
$white = imagecolorallocate($output, 255, 255, 255);
imagefilledrectangle($output, 0, 0, $width, $height, $white);
imagecopy($output, $input, 0, 0, 0, 0, $width, $height);
imagejpeg($output, $output_file);
}
}
?>
Its Image Processing and GD in PHP.
PHP Manual
Hope it helps, you can change it as you want.
Try this code: Imagick::setCompressionQuality
$im = new imagick(realpath($file).'[0]');
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(100);
$im->setImageFormat("jpeg");
$im->writeImage("imagename.jpg");
Alternative solution: this may help:
<?php
//Note that the function returns an Imagick object and does not modify the existing object. Below is my code for converting a PNG with transparency into a JPG with a background color. This code illustrates the difference.
$im = new Imagick($filename);
$im->setImageBackgroundColor('white');
$im->flattenImages(); // This does not do anything.
$im = $im->flattenImages(); // Use this instead.
$im->setImageFormat('jpg');
$im->writeImage('image.jpg');
?>
use like this
class ImageConvertorLib{
private $CI;
/**
* loading codeIgniter instance
*/
public function __construct(){
$this->CI =& get_instance();
}
public function pdfToJpg($param){
$filename = $param['filename'];
$image_name = $param['image_name'];
$path = $param['path'];
$db_path = $param['db_path'];
$im = new Imagick();
$im->setResolution(220,220);
$im->readimage($filename."[0]");
$im->setImageFormat('jpeg');
$im->setImageBackgroundColor('#ffffff');
$im->flattenImages();
$image_name = $image_name.".jpg";//"save_as_name.jpg";
$imageprops = $im->getImageGeometry();
/*if ($imageprops['width'] <= 175 && $imageprops['height'] <= 300) {
// don't upscale
} else {
$im->resizeImage(175,300, imagick::FILTER_LANCZOS, 0.9, true);
}*/
$im->writeImage($path.$image_name);
if($im){
$Img = array();
$Img['status'] = 1;
$Img['image'] = ($db_path.$image_name);
return $Img;
}
$im->clear();
$im->destroy();
}
}
After endless attempts to append a pdf file with a jpeg image without getting black areas, I found the solution: the function transformImageColorspace
Used in this order works perfectly:
$im = new Imagick();
$im->readImage("file.pdf");
$im->transformImageColorspace(Imagick::COLORSPACE_SRGB);
$im->setImageFormat('jpeg');
$im->writeImage('image.jpg');

S3 Image upload after GD resize PHP

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)){

Compress & save base64 image

My app is receiving base64-encoded image-files from the webbrowser. I need to save them on the client. So I did:
$data = base64_decode($base64img);
$fileName = uniqid() . '.jpg';
file_put_contents($uploadPath . $fileName, $data);
return $fileName;
Which works fine.
Now I need to compress & resize the image to max. 800 width & height, maintaining the aspect-ratio.
So I tried:
$data = base64_decode($base64img);
$fileName = uniqid() . '.jpg';
file_put_contents($uploadPath . $fileName, $data);
return $fileName;
which does not work (error: "imagejpeg() expects parameter 1 to be resource, string given").
And of course, this does compress, but not resize.
Would it be best to save the file in /tmp, read it and resize/move via GD?
Thanks.
2nd part
Thanks to #ontrack I know now that
$data = imagejpeg(imagecreatefromstring($data),$uploadPath . $fileName,80);
works.
But now I need to resize the image to max 800 width and height. I have this function:
function resizeAndCompressImagefunction($file, $w, $h, $crop=FALSE) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*($r-$w/$h)));
} else {
$height = ceil($height-($height*($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
$src = imagecreatefromjpeg($file);
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
So I thought I could do:
$data = imagejpeg(resizeAndCompressImagefunction(imagecreatefromstring($data),800,800),$uploadPath . $fileName,80);
which does not work.
You can use imagecreatefromstring
To answer the second part:
$data = imagejpeg(resizeAndCompressImagefunction(imagecreatefromstring($data),800,800),$uploadPath . $fileName,80);
$data will only contain either true or false to indicate wether the operation of imagejpeg was a success. The bytes are in $uploadPath . $fileName. If you want the actual bytes back in $data you have to use a temporary output buffer:
$img = imagecreatefromstring($data);
$img = resizeAndCompressImagefunction($img, 800, 800);
ob_start();
imagejpeg($img, null, 80);
$data = ob_get_clean();

Categories