I want to get this code working as described, it needs just to specify the path and I don't know where to add it.
This code is working will I want to add path to upload the image to specific folder ??
<?php
function image_resize($src, $dst, $width, $height, $crop=0){
if(!list($w, $h) = getimagesize($src)) return "Unsupported picture type!";
$type = strtolower(substr(strrchr($src,"."),1));
if($type == 'jpeg') $type = 'jpg';
switch($type){
case 'bmp': $img = imagecreatefromwbmp($src); break;
case 'gif': $img = imagecreatefromgif($src); break;
case 'jpg': $img = imagecreatefromjpeg($src); break;
case 'png': $img = imagecreatefrompng($src); break;
default : return "Unsupported picture type!";
}
// resize
if($crop){
if($w < $width or $h < $height) return "Picture is too small!";
$ratio = max($width/$w, $height/$h);
$h = $height / $ratio;
$x = ($w - $width / $ratio) / 2;
$w = $width / $ratio;
}
else{
if($w < $width and $h < $height) return "Picture is too small!";
$ratio = min($width/$w, $height/$h);
$width = $w * $ratio;
$height = $h * $ratio;
$x = 0;
}
$new = imagecreatetruecolor($width, $height);
// preserve transparency
if($type == "gif" or $type == "png"){
imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
imagealphablending($new, false);
imagesavealpha($new, true);
}
imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);
switch($type){
case 'bmp': imagewbmp($new, $dst); break;
case 'gif': imagegif($new, $dst); break;
case 'jpg': imagejpeg($new, $dst); break;
case 'png': imagepng($new, $dst); break;
}
return true;
}
if(isset($_POST['submitButton'])){
$picture=$_FILES['image1'];
$pic_type = strtolower(strrchr($picture['name'],"."));
$pic_name = "original$pic_type";
move_uploaded_file($picture['tmp_name'], $pic_name);
if (true !== ($pic_error = #image_resize($pic_name, "100x100$pic_type", 100, 100, 1))) {
echo $pic_error;
unlink($pic_name);
}
else echo "OK!";
}
?>
<form method="post" action="" enctype="multipart/form-data" >
<p>
<input type="file" name="image1" />
</p>
<input type="submit" name="submitButton" value="save"/>
</form>
I have solved this by adding the folder path to both $pic_name & "100x100$pic_type":)
The first and second arguments of your
image_resize($src, $dst, $width, $height, $crop=0) function take source path and destination path to picture respectively.
So in your code you should edit the following part:
$pic_name = "original$pic_type";
move_uploaded_file($picture['tmp_name'], $pic_name);
if (true !== ($pic_error = #image_resize($pic_name, "100x100$pic_type", 100, 100, 1))) {
Currently your source path is specified as "original$pic_type" and destination path is specified as "100x100$pic_type", you may change it somehow you want.
if(isset($_POST['submitButton'])){
//function image_resize($src, $dst, $width, $height, $crop=0)
$tmpName = $_FILES['image1']['tmp_name'];
image_resize($tmpName, '/where/you/want/your/file', 300, 300)
// width and height just set a minimal width and height for the picture)
}
What you want is $dst, altrought, you can make this code better.
EDIT: you must specify a folder and a file name in the $dst, if you don`t know the file ext, you can add $dst as a folder, and inside the function you add a file name to it, like:
$dst = "/myfolder/toupload/"
$file = myfilename.".".$type
$dst .= $file;
Related
I use this code in images.php to show the images :
imagepng($out);
and if i want to reduce the images quality for thumbnails i tried this code :
imagepng($out,$filename,$quality);
i want to know how to reduce image quality without saving.
function resize_image($file, $w, $h, $crop=false) {
list($width, $height) = getimagesize($file);
$r = $width / $height;
if ($crop) {
if ($width > $height) {
$width = ceil($width-($width*abs($r-$w/$h)));
} else {
$height = ceil($height-($height*abs($r-$w/$h)));
}
$newwidth = $w;
$newheight = $h;
} else {
if ($w/$h > $r) {
$newwidth = $h*$r;
$newheight = $h;
} else {
$newheight = $w/$r;
$newwidth = $w;
}
}
//Get file extension
$exploding = explode(".",$file);
$ext = end($exploding);
switch($ext){
case "png":
$src = imagecreatefrompng($file);
break;
case "jpeg":
case "jpg":
$src = imagecreatefromjpeg($file);
break;
case "gif":
$src = imagecreatefromgif($file);
break;
default:
$src = imagecreatefromjpeg($file);
break;
}
$dst = imagecreatetruecolor($newwidth, $newheight);
imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
return $dst;
}
$filename = "/var/www/images/mynormalimage.png";
$resizedFilename = "/var/www/images/myresizedimage.png";
// resize the image with 300x300
$imgData = resize_image($filename, 300, 300);
// save the image on the given filename
imagepng($imgData, $resizedFilename);
// or according to the original format, use another method
// imagejpeg($imgData, $resizedFilename);
// imagegif($imgData, $resizedFilename);
https://ourcodeworld.com/articles/read/197/how-to-resize-an-image-and-reduce-quality-in-php-without-imagickenter code here
I want to make a thumbnail(64X64) of images uploaded by user to reduce the overall page size. I did it using the following PHP code, But the result is really disappointing! in one instance the original file size was 554 byte (70X70). by converting it to a 64X64 image, the file size has increase to 1.43 KB! while the quality of the image is terribly degraded.
What is wrong here? Isn't it any other way to resize the images by PHP and have a better output?
Thank you very much
function image_resize($src, $dst, $width, $height, $crop=0){
if(!list($w, $h) = getimagesize($src)) return "Unsupported picture type!";
$type = strtolower(substr(strrchr($src,"."),1));
if($type == 'jpeg') $type = 'jpg';
switch($type){
case 'bmp': $img = imagecreatefromwbmp($src); break;
case 'gif': $img = imagecreatefromgif($src); break;
case 'jpg': $img = imagecreatefromjpeg($src); break;
case 'png': $img = imagecreatefrompng($src); break;
default : return "Unsupported picture type!";
}
// resize
if($crop){
if($w < $width or $h < $height) return "Picture is too small!";
$ratio = max($width/$w, $height/$h);
$h = $height / $ratio;
$x = ($w - $width / $ratio) / 2;
$w = $width / $ratio;
}
else{
if($w < $width and $h < $height) return "Picture is too small!";
$ratio = min($width/$w, $height/$h);
$width = $w * $ratio;
$height = $h * $ratio;
$x = 0;
}
$new = imagecreatetruecolor($width, $height);
// preserve transparency
if($type == "gif" or $type == "png"){
imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
imagealphablending($new, false);
imagesavealpha($new, true);
}
imagecopyresampled($new, $img, 0, 0, $x, 0, $width, $height, $w, $h);
switch($type){
case 'bmp': imagewbmp($new, $dst); break;
case 'gif': imagegif($new, $dst); break;
case 'jpg': imagejpeg($new, $dst); break;
case 'png': imagepng($new, $dst); break;
}
return true;
}
I think that probably nothing is wrong here. 1.43KB is not very much, so it's not clear that the image produced is inefficiently stored. As for image quality, we're talking about a very small image; resizing from 70x70 to 64x64 is very likely to produce an odd-looking result. If you have a larger image to start with then it will probably work better.
There are other PHP image libraries (e.g. WideImage), but I'd be surprised if using them would make a great deal of difference here. In fact they probably use GD internally anyway.
I am using this class:
class ImgResizer {
function ImgResizer($originalFile = '$newName') {
$this -> originalFile = $originalFile;
}
function resize($newWidth, $targetFile) {
if (empty($newWidth) || empty($targetFile)) {
return false;
}
$src = imagecreatefromjpeg($this -> originalFile);
list($width, $height) = getimagesize($this -> originalFile);
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
imagejpeg($tmp, $targetFile, 95);
}
}
Which works excellently, but it fails with png's, it creates a resized black image.
Is there a way to tweak this class to support png images?
function resize($newWidth, $targetFile, $originalFile) {
$info = getimagesize($originalFile);
$mime = $info['mime'];
switch ($mime) {
case 'image/jpeg':
$image_create_func = 'imagecreatefromjpeg';
$image_save_func = 'imagejpeg';
$new_image_ext = 'jpg';
break;
case 'image/png':
$image_create_func = 'imagecreatefrompng';
$image_save_func = 'imagepng';
$new_image_ext = 'png';
break;
case 'image/gif':
$image_create_func = 'imagecreatefromgif';
$image_save_func = 'imagegif';
$new_image_ext = 'gif';
break;
default:
throw new Exception('Unknown image type.');
}
$img = $image_create_func($originalFile);
list($width, $height) = getimagesize($originalFile);
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
$image_save_func($tmp, "$targetFile.$new_image_ext");
}
I've written a class that will do just that and is nice and easy to use. It's called
PHP Image Magician
$magicianObj = new imageLib('racecar.jpg');
$magicianObj -> resizeImage(100, 200);
$magicianObj -> saveImage('racecar_convertd.png', 100);
It supports Read and Write (including converting) the following formats
jpg
png
gif
bmp
And can read only
psd's
Example
// Include PHP Image Magician library
require_once('php_image_magician.php');
// Open JPG image
$magicianObj = new imageLib('racecar.jpg');
// Resize to best fit then crop
$magicianObj -> resizeImage(100, 200, 'crop');
// Save resized image as a PNG
$magicianObj -> saveImage('racecar_small.png');
You can try this. Currently it's assuming the image will always be a jpeg. This will allow you to load a jpeg, png, or gif. I haven't tested but it should work.
function resize($newWidth, $targetFile) {
if (empty($newWidth) || empty($targetFile)) {
return false;
}
$fileHandle = #fopen($this->originalFile, 'r');
//error loading file
if(!$fileHandle) {
return false;
}
$src = imagecreatefromstring(stream_get_contents($fileHandle));
fclose($fileHandle);
//error with loading file as image resource
if(!$src) {
return false;
}
//get image size from $src handle
list($width, $height) = array(imagesx($src), imagesy($src));
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $src, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
//allow transparency for pngs
imagealphablending($tmp, false);
imagesavealpha($tmp, true);
if (file_exists($targetFile)) {
unlink($targetFile);
}
//handle different image types.
//imagepng() uses quality 0-9
switch(strtolower(pathinfo($this->originalFile, PATHINFO_EXTENSION))) {
case 'jpg':
case 'jpeg':
imagejpeg($tmp, $targetFile, 95);
break;
case 'png':
imagepng($tmp, $targetFile, 8.5);
break;
case 'gif':
imagegif($tmp, $targetFile);
break;
}
//destroy image resources
imagedestroy($tmp);
imagedestroy($src);
}
Try this one and using this you can also save your image to specific path.
function resize($file, $imgpath, $width, $height){
/* Get original image x y*/
list($w, $h) = getimagesize($file['tmp_name']);
/* calculate new image size with ratio */
$ratio = max($width/$w, $height/$h);
$h = ceil($height / $ratio);
$x = ($w - $width / $ratio) / 2;
$w = ceil($width / $ratio);
/* new file name */
$path = $imgpath;
/* read binary data from image file */
$imgString = file_get_contents($file['tmp_name']);
/* create image from string */
$image = imagecreatefromstring($imgString);
$tmp = imagecreatetruecolor($width, $height);
imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h);
/* Save image */
switch ($file['type']) {
case 'image/jpeg':
imagejpeg($tmp, $path, 100);
break;
case 'image/png':
imagepng($tmp, $path, 0);
break;
case 'image/gif':
imagegif($tmp, $path);
break;
default:
//exit;
break;
}
return $path;
/* cleanup memory */
imagedestroy($image);
imagedestroy($tmp);
}
Now you need to call this function while saving image as like...
<?php
//$imgpath = "Where you want to save your image";
resize($_FILES["image"], $imgpath, 340, 340);
?>
I took the P. Galbraith's version, fixed the errors and changed it to resize by area (width x height). For myself, I wanted to resize images that are too big.
function resizeByArea($originalFile,$targetFile){
$newArea = 375000; //a little more than 720 x 480
list($width,$height,$type) = getimagesize($originalFile);
$area = $width * $height;
if($area > $newArea){
if($width > $height){ $big = $width; $small = $height; }
if($width < $height){ $big = $height; $small = $width; }
$ratio = $big / $small;
$newSmall = sqrt(($newArea*$small)/$big);
$newBig = $ratio*$newSmall;
if($width > $height){ $newWidth = round($newBig, 0); $newHeight = round($newSmall, 0); }
if($width < $height){ $newWidth = round($newSmall, 0); $newHeight = round($newBig, 0); }
}
switch ($type) {
case '2':
$image_create_func = 'imagecreatefromjpeg';
$image_save_func = 'imagejpeg';
$new_image_ext = '.jpg';
break;
case '3':
$image_create_func = 'imagecreatefrompng';
// $image_save_func = 'imagepng';
// The quality is too high with "imagepng"
// but you need it if you want to allow transparency
$image_save_func = 'imagejpeg';
$new_image_ext = '.png';
break;
case '1':
$image_create_func = 'imagecreatefromgif';
$image_save_func = 'imagegif';
$new_image_ext = '.gif';
break;
default:
throw Exception('Unknown image type.');
}
$img = $image_create_func($originalFile);
$tmp = imagecreatetruecolor($newWidth,$newHeight);
imagecopyresampled( $tmp, $img, 0, 0, 0, 0,$newWidth,$newHeight, $width, $height );
ob_start();
$image_save_func($tmp);
$i = ob_get_clean();
// if file exists, create a new one with "1" at the end
if (file_exists($targetFile.$new_image_ext)){
$targetFile = $targetFile."1".$new_image_ext;
}
else{
$targetFile = $targetFile.$new_image_ext;
}
$fp = fopen ($targetFile,'w');
fwrite ($fp, $i);
fclose ($fp);
unlink($originalFile);
}
If you want to allow transparency, check this : http://www.akemapa.com/2008/07/10/php-gd-resize-transparent-image-png-gif/
I tested the function, it works fine!
the accepted answer has alot of errors here is it fixed
<?php
function resize($newWidth, $targetFile, $originalFile) {
$info = getimagesize($originalFile);
$mime = $info['mime'];
switch ($mime) {
case 'image/jpeg':
$image_create_func = 'imagecreatefromjpeg';
$image_save_func = 'imagejpeg';
$new_image_ext = 'jpg';
break;
case 'image/png':
$image_create_func = 'imagecreatefrompng';
$image_save_func = 'imagepng';
$new_image_ext = 'png';
break;
case 'image/gif':
$image_create_func = 'imagecreatefromgif';
$image_save_func = 'imagegif';
$new_image_ext = 'gif';
break;
default:
throw Exception('Unknown image type.');
}
$img = $image_create_func($originalFile);
list($width, $height) = getimagesize($originalFile);
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($tmp, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
if (file_exists($targetFile)) {
unlink($targetFile);
}
$image_save_func($tmp, "$targetFile.$new_image_ext");
}
$img=$_REQUEST['img'];
$id=$_REQUEST['id'];
// echo $img
resize(120, $_SERVER['DOCUMENT_ROOT'] ."/images/$id",$_SERVER['DOCUMENT_ROOT'] ."/images/$img") ;
?>
I know this is very old thread, but I found PHP has imagescale function built in, which does the required job. See documentation here
Example usage:
$temp = imagecreatefrompng('1.png');
$scaled_image= imagescale ( $temp, 200 , 270);
Here 200 is width and 270 is height of resized image.
I want to have a function that resizes to a specific height en weight of an image without losing the aspect ratio. So first i want to crop it and then resizing it.
This is what i got so far:
function image_resize($src, $dst, $width, $height, $crop=1){
if(!list($w, $h) = getimagesize($src)) return "Unsupported picture type!";
$type = strtolower(substr(strrchr($src,"."),1));
if($type == 'jpeg') $type = 'jpg';
switch($type){
case 'bmp': $img = imagecreatefromwbmp($src); break;
case 'gif': $img = imagecreatefromgif($src); break;
case 'jpg': $img = imagecreatefromjpeg($src); break;
case 'png': $img = imagecreatefrompng($src); break;
default : return "Unsupported picture type!";
}
// resize
$originalW = $w;
$originalH = $h;
if($crop){
if($w < $width or $h < $height) return "Picture is too small!";
$ratio = max($width/$w, $height/$h);
$h = $height / $ratio;
$x = ($w - $width / $ratio) / 2;
$w = $width / $ratio;
}
else{
if($w < $width and $h < $height) return "Picture is too small!";
$ratio = min($width/$w, $height/$h);
$width = $w * $ratio;
$height = $h * $ratio;
$x = 0;
}
$new = imagecreatetruecolor($width, $height);
// preserve transparency
if($type == "gif" or $type == "png"){
imagecolortransparent($new, imagecolorallocatealpha($new, 0, 0, 0, 127));
imagealphablending($new, false);
imagesavealpha($new, true);
}
imagecopyresampled($new, $img, 0, 0, ($originalW - $width)/2, ($originalH - $height)/2, $width, $height, $w, $h);
switch($type){
case 'bmp': imagewbmp($new, $dst); break;
case 'gif': imagegif($new, $dst); break;
case 'jpg': imagejpeg($new, $dst); break;
case 'png': imagepng($new, $dst); break;
}
return true;
}
The function is working fine. But i still have a problem. For example: When i resize a portrait image thats (300 × 450) to (260 x 140) i get a black side bar which i dont want.
Here are the 2 images:
It worked for me. You can try:
$x=288; $y=202; // my final thumb
$ratio_thumb=$x/$y; // ratio thumb
list($xx, $yy) = getimagesize($image); // original size
$ratio_original=$xx/$yy; // ratio original
if ($ratio_original>=$ratio_thumb) {
$yo=$yy;
$xo=ceil(($yo*$x)/$y);
$xo_ini=ceil(($xx-$xo)/2);
$xy_ini=0;
} else {
$xo=$xx;
$yo=ceil(($xo*$y)/$x);
$xy_ini=ceil(($yy-$yo)/2);
$xo_ini=0;
}
imagecopyresampled($thumb, $source, 0, 0, $xo_ini, $xy_ini, $x, $y, $xo, $yo);
works fine with:
imagecopyresampled($new, $img, 0, 0, 0, 0, $width, $height, $w, $h);
I upload the image to my site. Image has width is 498 and height is 402.
I need to make a preview image with the established maximum width of 250px and a maximum height of 250px, but the image should be 250 to 250, and must be proportional to the width of 250 pixels.
How to do it?
EDIT
I upload images to your server. The limit on the size I want to make 250 in width and 250 in height.
This does not mean that if I upload an image 1000h500, then it must do 250x250, which means that the width we're doing 250 pixels and the height is proportional to the first dimension is 125. In the end, I should get a picture 250x125.
Second example: I have an image 100h800. I mean it should be changed
Here's a function I wrote for generating thumbnails using GD. You can pass a max width or height, or both (if zero, means unrestricted) and the thumbnail will be scaled to $dest (+ file extension) with proportions intact. It also works on transparent images. Any extra space left should be fully transparent; If you want a different background, modify $img before the imagecopyresampled() on it.
function picThumb($src, $dest, $width = 0, $height = 0, $quality = 100)
{
$srcType = exif_imagetype($src);
if (!$width && !$height)
{
$ext = image_type_to_extension($srcType, false);
copy($src, $dest . '.' . $ext);
return $ext;
}
ini_set('memory_limit', '134217728');
try
{
switch ($srcType)
{
case IMAGETYPE_JPEG:
$srcImg = imagecreatefromjpeg($src);
break;
case IMAGETYPE_PNG:
$srcImg = imagecreatefrompng($src);
break;
case IMAGETYPE_GIF:
$srcImg = imagecreatefromgif($src);
break;
default:
throw new Exception();
}
$srcWidth = imagesx($srcImg);
$srcHeight = imagesy($srcImg);
if (!$srcWidth || !$srcHeight)
{
throw new Exception();
}
if ($width && $height)
{
$ratio = min($srcWidth / $width, $srcHeight / $height);
$areaWidth = round($width * $ratio);
$areaHeight = round($height * $ratio);
$areaX = round(($srcWidth - $areaWidth) / 2);
$areaY = round(($srcHeight - $areaHeight) / 2);
}
else // if (!$width || !$height)
{
if ($width)
{
$height = round($width / $srcWidth * $srcHeight);
}
else // if ($height)
{
$width = round($height / $srcHeight * $srcWidth);
}
$areaWidth = $srcWidth;
$areaHeight = $srcHeight;
$areaX = 0;
$areaY = 0;
}
$img = imagecreatetruecolor($width, $height);
imagealphablending($img, false);
imagecopyresampled($img, $srcImg, 0, 0, $areaX, $areaY, $width, $height, $areaWidth, $areaHeight);
switch ($srcType)
{
case IMAGETYPE_JPEG:
$ext = 'jpg';
imagejpeg($img, $dest . '.' . $ext, $quality);
break;
case IMAGETYPE_PNG:
case IMAGETYPE_GIF:
$ext = 'png';
imagesavealpha($img, true);
imagepng($img, $dest . '.' . $ext, 9);
break;
default:
throw new Exception();
}
imagedestroy($srcImg);
imagedestroy($img);
}
catch (Exception $e)
{
ini_restore('memory_limit');
throw $e;
}
ini_restore('memory_limit');
return $ext;
}
I recommend to use ImageMagick class for this purposes.
Some strings of code, how to make 250x250 image and save it:
$img = new Imagick('/path/to/image/image.jpg'); //image.jpg - your file
$img->cropThumbnailImage(250, 250); //make thumbnail 250x250
$img->writeImage('/newptah/newfilename.jpg'); //write thumbnail to new path
$img->destroy(); //free resources
newfilename.jpg - would be 250x250 square without losing proportions.
you can use getimagesize function. it will return an array
$size = getimagesize($filename);
$width = $size[0];
$height => $size[1];
Then, since width of your image is greater than height, multiply the original width and height by 250/498
function makeThumbnail($image, $dest)
{
$imageType = exif_imagetype($image);
switch ($imageType)
{
case IMAGETYPE_JPEG:
$img = imagecreatefromjpeg($image);
break;
case IMAGETYPE_PNG:
$img = imagecreatefrompng($image);
break;
case IMAGETYPE_GIF:
$img = imagecreatefromgif($image);
break;
default:
throw new Im_Exception('Bad extension');
}
$width = imagesx($img);
$height = imagesy($img);
if ($height > $width)
{
$ratio = 250 / $height;
$newHeight = 250;
$newWidth = $width * $ratio;
}
else
{
$ratio = 250 / $width;
$newWidth = 250;
$newHeight = $height * $ratio;
}
$previewImg = imagecreatetruecolor($newWidth, $newHeight);
$palsize = ImageColorsTotal($img);
for ($i = 0; $i < $palsize; $i++)
{
$colors = ImageColorsForIndex($img, $i);
ImageColorAllocate($previewImg, $colors['red'], $colors['green'], $colors['blue']);
}
imagecopyresized($previewImg, $img, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
switch ($imageType)
{
case IMAGETYPE_JPEG:
$ext = 'jpg';
imagejpeg($previewImg, $dest . '.' . $ext);
break;
case IMAGETYPE_PNG:
case IMAGETYPE_GIF:
$ext = 'png';
imagesavealpha($previewImg, true);
imagepng($previewImg, $dest . '.' . $ext, 9);
break;
default:
throw new Im_Exception();
}
imagedestroy($previewImg);
imagedestroy($img);
}