I have the following problem. I use ImageMagick for the reformat PDF to JPG. Everything goes well but on the picture appear the mark in the form of triangles. Here is an example code and images before and after.
$pdf_file = $name[0] . '.pdf';
$im = new imagick($pdf_file);
$i = 0;
foreach ($im as $_img) {
$i++;
$_img->setResolution(300, 300);
$im->setImageColorspace(255);
$im->setCompression(Imagick::COMPRESSION_JPEG);
$im->setCompressionQuality(60);
$_img->setImageFormat('jpg');
$_img->writeImage(__DIR__ .'/'.$main_name[0] . '.jpg');
}
$im->destroy();
$new_name = DIR .'/'. $main_name[0] . '.jpg';
$new_name1 = $main_name[0] . '.jpg';
//$new_name1 = preg_replace('/[^A-Za-z0-9\-]/', '', $new_name1);
$size = getimagesize($new_name1);
$ratio = $size[0]/$size[1]; // width/height
if( $ratio > 1) {
$width = 700;
$height = 700/$ratio;
}
else {
$width = 700*$ratio;
$height = 700;
}
$src = imagecreatefromstring(file_get_contents($new_name1));
$dst = imagecreatetruecolor($width,$height);
imagecopyresampled($dst,$src,0,0,0,0,$width,$height,$size[0],$size[1]);
imagedestroy($src);
imagepng($dst,$new_name1); // adjust format as needed
imagedestroy($dst);
The "stains" are JPEG artifacts. Use a higher "quality" (60 is pretty low; 90 would be better for this type of image), or use PNG instead. The higher-quality JPEG will of course occupy a larger filesize, but that's the tradeoff.
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.
//Your Image
$imgSrc = $_GET['f'];
list($width, $height) = getimagesize($imgSrc);
list($root) = explode('httpdocs', __FILE__);
$root = $root.'httpdocs';
$savePath = $root.'/_m/chacheImages/';
$savePath = '../cacheImages/';
$imgName = basename($imgSrc);
list($imgName) = explode('.', $imgName);
$fileName = $savePath.$imgName.'.jpg';
if($width > 0 && $height > 0){
$thumbSize = 100;
$img_p = imagecreatetruecolor($width, $height);
$img = imagecreatefrompng($imgSrc);
imagecopyresampled($img_p, $img, -10, 0, 0, 10, $width+30, $height, ($width), ($height-20));
//header('Content-type: image/png');
imagejpeg($img_p, $fileName);
imagedestroy($img_p);
}
I can't seem to get this to work. If i delete $fileName at imagejpeg it shows the image correctly.
But it won't save the images. What am I doing wrong?
I have the following in place for all my images in /images/500x500/. I need to resize the images to 250x250 and have them go into the /images/250x250/ with the same filename.
It doesn't create the new image in the new directory, rather it replaces the large in the same directory?
<?php
$files = glob("*.{png,jpg,jpeg}", GLOB_BRACE);
foreach ($files as $file)
{
// get the image size
$imagesize = getimagesize($file);
$width_orig = $imagesize[0];
$height_orig = $imagesize[1];
$dst_w = 250;
if($width_orig != $dst_w)
{
$dst_h_multiplier = $dst_w / $width_orig;
$dst_h = $dst_h_multiplier * $height_orig;
$dst = imagecreatetruecolor($dst_w, $dst_h);
$image = imagecreatefromjpeg($file);
imagecopyresampled($dst, $image, 0, 0, 0, 0, $dst_w, $dst_h ,$width_orig, $height_orig);
imagejpeg($dst, $outputFile, 100);
$outputFile =
realpath(
pathinfo($file, PATHINFO_DIRNAME)
. '/../250x250/'
) . pathinfo($file, PATHINFO_BASENAME);
}
}
?>
$outputFile =
realpath(
pathinfo($file, PATHINFO_DIRNAME)
. '/../'
) . pathinfo($file, PATHINFO_BASENAME);
First, you need the path, which you can get with realpath(), along with pathinfo(). Then, just append a .. and the file name.
http://www.php.net/manual/en/function.pathinfo.php
http://php.net/manual/en/function.realpath.php
Also, you might not need realpath(). I haven't tested.
In one of my applications, I'm using the code snippet below to copy uploaded images to a directory. It works fine but copying large images (> 2MB) takes more time than ideal and I really don't need images this big, so, I'm looking for a way to resize the images. How to achieve this using PHP?
<?php
$uploadDirectory = 'images/0001/';
$randomNumber = rand(0, 99999);
$filename = basename($_FILES['userfile']['name']);
$filePath = $uploadDirectory.md5($randomNumber.$filename);
// Check if the file was sent through HTTP POST.
if (is_uploaded_file($_FILES['userfile']['tmp_name']) == true) {
// Validate the file size, accept files under 5 MB (~5e+6 bytes).
if ($_FILES['userfile']['size'] <= 5000000) {
// Move the file to the path specified.
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $filePath) == true) {
// ...
}
}
}
?>
Finally, I've discovered a way that fit my needs. The following snippet will resize an image to the specified width, automatically calculating the height in order to keep the proportion.
$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";
copy($_FILES, $resizedDestination);
$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);
$originalImage = imageCreateFromJPEG($image);
$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);
imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);
imageDestroy($originalImage);
imageDestroy($resizedImage);
To anyone else seeking a complete example, create two files:
<!-- send.html -->
<html>
<head>
<title>Simple File Upload</title>
</head>
<body>
<center>
<div style="margin-top:50px; padding:20px; border:1px solid #CECECE;">
Select an image.
<br/>
<br/>
<form action="receive.php" enctype="multipart/form-data" method="post">
<input type="file" name="image" size="40">
<input type="submit" value="Send">
</form>
</div>
</center>
</body>
<?php
// receive.php
$randomNumber = rand(0, 99999);
$uploadDirectory = "images/";
$filename = basename($_FILES['file_contents']['name']);
$destination = $uploadDirectory.md5($randomNumber.$filename).".jpg";
echo "File path:".$filePath."<br/>";
if (is_uploaded_file($_FILES["image"]["tmp_name"]) == true) {
echo "File successfully received through HTTP POST.<br/>";
// Validate the file size, accept files under 5 MB (~5e+6 bytes).
if ($_FILES['image']['size'] <= 5000000) {
echo "File size: ".$_FILES["image"]["size"]." bytes.<br/>";
// Resize and save the image.
$image = $_FILES["image"]["tmp_name"];
$resizedDestination = $uploadDirectory.md5($randomNumber.$filename)."_RESIZED.jpg";
copy($_FILES, $resizedDestination);
$imageSize = getImageSize($image);
$imageWidth = $imageSize[0];
$imageHeight = $imageSize[1];
$DESIRED_WIDTH = 100;
$proportionalHeight = round(($DESIRED_WIDTH * $imageHeight) / $imageWidth);
$originalImage = imageCreateFromJPEG($image);
$resizedImage = imageCreateTrueColor($DESIRED_WIDTH, $proportionalHeight);
imageCopyResampled($images_fin, $originalImage, 0, 0, 0, 0, $DESIRED_WIDTH+1, $proportionalHeight+1, $imageWidth, $imageHeight);
imageJPEG($resizedImage, $resizedDestination);
imageDestroy($originalImage);
imageDestroy($resizedImage);
// Save the original image.
if (move_uploaded_file($_FILES['image']['tmp_name'], $destination) == true) {
echo "Copied the original file to the specified destination.<br/>";
}
}
}
?>
I made a small function to resize images, the function is below:
function resize_image($path, $width, $height, $update = false) {
$size = getimagesize($path);// [width, height, type index]
$types = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
if ( array_key_exists($size['2'], $types) ) {
$load = 'imagecreatefrom' . $types[$size['2']];
$save = 'image' . $types[$size['2']];
$image = $load($path);
$resized = imagecreatetruecolor($width, $height);
$transparent = imagecolorallocatealpha($resized, 0, 0, 0, 127);
imagesavealpha($resized, true);
imagefill($resized, 0, 0, $transparent);
imagecopyresampled($resized, $image, 0, 0, 0, 0, $width, $height, $size['0'], $size['1']);
imagedestroy($image);
return $save($resized, $update ? $path : null);
}
}
And here's how you use it:
if ( resize_image('dir/image.png', 50, 50, true) ) {// resize image.png to 50x50
echo 'image resized!';
}
there is 1 very simple image re-size function for all image types that keeps transparency and is very easy to use
check out :
https://github.com/Nimrod007/PHP_image_resize
hope this helps
ImageMagick is the fastest and probably the best way to resize images in PHP. Check out different examples here. This sample shows how to resize and image on upload.
Thanks to Mateus Nunes!
i edited his work a bit to get transparent pngs working:
$source = $_FILES["..."]["tmp_name"];
$destination = 'abc/def/ghi.png';
$maxsize = 45;
$size = getimagesize($source);
$width_orig = $size[0];
$height_orig = $size[1];
unset($size);
$height = $maxsize+1;
$width = $maxsize;
while($height > $maxsize){
$height = round($width*$height_orig/$width_orig);
$width = ($height > $maxsize)?--$width:$width;
}
unset($width_orig,$height_orig,$maxsize);
$images_orig = imagecreatefromstring( file_get_contents($source) );
$photoX = imagesx($images_orig);
$photoY = imagesy($images_orig);
$images_fin = imagecreatetruecolor($width,$height);
imagesavealpha($images_fin,true);
$trans_colour = imagecolorallocatealpha($images_fin,0,0,0,127);
imagefill($images_fin,0,0,$trans_colour);
unset($trans_colour);
ImageCopyResampled($images_fin,$images_orig,0,0,0,0,$width+1,$height+1,$photoX,$photoY);
unset($photoX,$photoY,$width,$height);
imagepng($images_fin,$destination);
unset($destination);
ImageDestroy($images_orig);
ImageDestroy($images_fin);
You could also use an x*y/width method for resizing and then calling imagecopyresampled() like is shown at http://www.virtualsecrets.com/upload-resize-image-php-mysql.html That page also puts images (after resizing) into mySQL via the PDO.