I am using imagick (PHP) version to basically add text and a logo to an animated gif. I have managed to add text which is great. But i am struggling to add an image using the following:
$gif = new Imagick();
$gif->readImage('images/highres/bg/' . $bgimg . '.gif');
foreach ($gif as $frame) {
$img = new Imagick();
$img->readImageBlob($frame);
$canvas->addImage( $img );
//$canvas->compositeImage($img, Imagick::COMPOSITE_DEFAULT, 0, 0); NOT WORKING
$canvas->setImageDelay( $img->getImageDelay() );
//$img->clear();
//Add Logo
//$logo = new Imagick();
//$logo->readImage('images/uploads/155x100.jpg');
//$canvas->compositeImage($logo, Imagick::COMPOSITE_DEFAULT, 500, 500); NOT WORKING
//$canvas->addImage( $logo );
}
Futhermore, i am struggling to position using X,Y coordinates.
Any ideas?
Might this can help you out.
<?php
if (isset($_FILES["file"])) {
$tmpFile = $_FILES["file"]["tmp_name"];
$fileName = ... // determine secure name for uploaded file
list($width, $height) = getimagesize($tmpFile);
// check if the file is really an image
if ($width == null && $height == null) {
header("Location: index.php");
return;
}
// resize if necessary
if ($width >= 400 && $height >= 400) {
$image = new Imagick($tmpFile);
$image->thumbnailImage(400, 400);
$image->writeImage($fileName);
}
else {
move_uploaded_file($tmpFile, $fileName);
}
}
Related
i tried to resize an image with following method:
code
$thumbimg = $img->resizeImage($thumb, 200, 200);
public function resizeImage($imagePath,$new_width,$new_height) {
$fileName = pathinfo($imagePath,PATHINFO_FILENAME);
$ext = pathinfo($imagePath,PATHINFO_EXTENSION);
$fullPath = pathinfo($imagePath,PATHINFO_DIRNAME)."/".$fileName.'.'.$ext;
if (file_exists($fullPath)) {
return $fullPath;
}
$image = $this->openImage($imagePath);
if ($image == false) {
return null;
}
$width = imagesx($image);
$height = imagesy($image);
$imageResized = imagecreatetruecolor($width, $height);
if ($imageResized == false) {
return null;
}
$image = imagecreatetruecolor($width , $height);
$imageResized = imagescale($image,$new_width,$new_height);
touch($fullPath);
$write = imagepng($imageResized,$fullPath);
if (!$write) {
imagedestroy($imageResized);
return null;
}
imagedestroy($imageResized);
return $fullPath;
}
Actual its saves my images in the original width and height. But why? Whats wrong?
If $imagePath refers to an existing image, then $fullPath will refer to that same file. So either the file exists, in which case it is returned, or the file does not exist, in which case you can't open the image and null is returned. Either way, the image resize code is not used.
I'm using imagick for image uploads and resizing. when I try to resize GIF image with vector graphics it won't resize as original. but normal animated giphys are woring. please advice
https://giphy.com/explore/vector-design
these giphs are not resizing with correct animation.
below is my code.
$imagick = new Imagick($_FILES['file']['tmp_name']);
foreach ($imageFolders as $imageFolder => $size) {
if ($imagick->getImageWidth() > $size['minWidth']) {
$width = $size['maxWidth'];
$height = $size['maxWidth'];
} else {
$width = $imagick->getImageWidth();
$height = $imagick->getImageHeight(
}
$imagick = $imagick->coalesceImages();
foreach($imagick as $frame){
$frame->thumbnailImage($width , $height );
$frame->setImagePage($width , $height , 0, 0);
}
$imagick = $imagick->deconstructImages();
$imagick->writeImages($imagePath, true);
}
$imagick->clear();
$imagick->destroy();
I'm using Imagick PHP extension for resizing GIF images to several sizes. When I trying with a GIF image of 3mb size, it doesn't get resized. But for images less than 1mb, they are getting resized successfully.
If anyone else has faced this problem, please advise!
Here my code
if ($extension === 'gif') {
$imagick = new Imagick($_FILES['file']['tmp_name']);
foreach ($imageFolders as $imageFolder => $size) {
if ($imagick->getImageWidth() > $size['minWidth']) {
$width = $size['maxWidth'];
$height = $size['maxWidth'];
} else {
$width = $imagick->getImageWidth();
$height = $imagick->getImageHeight();
}
$imagick->coalesceImages();
do {
$imagick->scaleImage($width, $height, Imagick::FILTER_BOX, 1);
} while ($imagick->nextImage());
$imagick = $imagick->deconstructImages();
$imagick->writeImages($imagePath, true);
}
$imagick->clear();
$imagick->destroy();
}
Result : convert list resource
File Area Memory Map Disk Thread Time
-------------------------------------------------------------------------------
768 7.951GB 3.7025GiB 7.4049GiB unlimited 2 unlimited
$imagick = new Imagick($_FILES['file']['tmp_name']);
foreach ($imageFolders as $imageFolder => $size) {
if ($imagick->getImageWidth() > $size['minWidth']) {
$width = $size['maxWidth'];
$height = $size['maxWidth'];
} else {
$width = $imagick->getImageWidth();
$height = $imagick->getImageHeight(
}
$imagick = $imagick->coalesceImages();
foreach($imagick as $frame){
$frame->thumbnailImage($width , $height );
$frame->setImagePage($width , $height , 0, 0);
}
$imagick = $imagick->deconstructImages();
$imagick->writeImages($imagePath, true);
}
$imagick->clear();
$imagick->destroy();
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;
}
Hi I based this function from the one I've found on web and tried modifying it up for my PHP page for uploading of their icons but I want to limit the user from uploading an image which should only size 100x100px. Well I just call it using this:
uploadImage($id,$_FILES['upload']['name'],$_FILES['upload']['tmp_name']);
This is the function I made:
function uploadImage($new_name,$imagename,$tmp_name){
if($tmp_name!=null||$tmp_name!=""){
list($width, $height, $type, $attr) = getimagesize($tmp_name);
if($width==100&&$height==100){
$image1 = $imagename;
$extension = substr($image1, strrpos($image1, '.') + 1);
$image = "$new_name.$extension";
$folder = "Images/";
if($image) {
$filename = $folder.$image;
$copied = copy($tmp_name, $filename);
}
else echo "image not uploaded.";
}
else
echo "upload only 100x100px image!";
}
}
Now the problem is that even if I uploaded an image which exceeds the 100 x 100px dimensions it still proceeds without returning any errors and now I'm lost with it.
You probably need to re-factor your code a bit; have a function that checks whether the uploaded image is valid, and then one actually does the upload. Alternatively, you could create a class.
<?php
class ImageUpload
{
public $tmpImage;
public $maxWidth = 100;
public $maxHeight = 100;
public $errors = [];
public function __construct($image)
{
$this->tmpImage = $image;
}
public function upload()
{
// Check image is valid; if not throw exception
// Check image is within desired dimensions
list($width, $height) = getimagesize($this->tmpImage);
if ($width > $this->maxWidth || $height > $this->maxHeight) {
throw new Exception(sprintf('Your image exceeded the maximum dimensions (%d×%d)', $this->maxWidth, $this->maxHeight));
}
// Create filename
// Do the upload logic, i.e. move_uploaded_file()
}
}
You can then use this class as follows:
<?php
$imageUpload = new ImageUpload($_FILES['upload']['tmp_name']);
try {
$imageUpload->upload();
} catch (Exception $e) {
echo 'An error occurred: ' . $e->getMessage();
}
This was written off the cuff, so they may be errors. But hopefully it demonstrates a better way to handle file uploads, and errors that may occur during upload.
well, you can also resize the image after upload.
function createFixSizeImage( $pathToImages, $pathToFixSizeImages, $Width )
{
// open the directory
$dir = opendir( $pathToImages );
// loop through it, looking for any/all JPG files:
while (false !== ($fname = readdir( $dir ))) {
$image_info = getimagesize( "path/to/images/".$fname );
$image_width = $image_info[0];
$image_height = $image_info[1];
$image_type = $image_info[2];
switch ( $image_type )
{
case IMAGETYPE_JPEG:
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'jpeg' )
{
// load image and get image size
$img = imagecreatefromjpeg( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
// give the size,u want
$new_width = 100;
$new_height = 100;
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save Fix Size Images into a file
imagejpeg( $tmp_img, "{$pathToFixSizeImages}{$fname}" );
}
break;
case IMAGETYPE_PNG:
// parse path for the extension
$info = pathinfo($pathToImages . $fname);
// continue only if this is a JPEG image
if ( strtolower($info['extension']) == 'png' )
{
// load image and get image size
$img = imagecreatefrompng( "{$pathToImages}{$fname}" );
$width = imagesx( $img );
$height = imagesy( $img );
$new_width = 100;
$new_height = 100;
// create a new temporary image
$tmp_img = imagecreatetruecolor( $new_width, $new_height );
// copy and resize old image into new image
imagecopyresized( $tmp_img, $img, 0, 0, 0, 0, $new_width, $new_height, $width, $height );
// save Fix Size Images into a file
imagejpeg( $tmp_img, "{$pathToFixSizeImages}{$fname}" );
}
break;
case IMAGETYPE_BMP:
echo "bmp";
break;
default:
break;
}
}
}
// close the directory
closedir( $dir );
}
createFixSizeImage("path","path/to/images/to/be/saved",100);
Extending more or less unknown code and then debugging it, is like you wrote some code weeks ago and you don't understand it any longer.
In your case you are extending some existing code (you have not posted the original code, but your wrote that you did it that way) by adding the feature of checking the image size.
So that you do not need to edit much of the (unknown but) working code, create the new feature as a function of it's own:
/**
* #param string $file
* #param int $with
* #param int $height
* #return bool|null true/false if image has that exact size, null on error.
*/
function image_has_size($file, $width, $height)
{
$result = getimagesize($file);
if ($count($result) < 2) {
return null;
}
list($file_width, $file_height) = $result;
return ($file_width == (int) $width)
&& ($file_height == (int) $height);
}
You now have the new functionality in a single function you can much more easily integrate into the original (hopefully otherwise working) code.
Usage:
$imageHasCorrectSize = image_has_size($tmp_name, 100, 100);
So whenever you change code, do it like a surgeon, keeping the cuts as small as possible.