PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label imagick. Show all posts
Showing posts with label imagick. Show all posts

Tuesday, October 11, 2022

[FIXED] How to implement imagecopy (GD) function by Imagick?

 October 11, 2022     gd, imagemagick, imagick, php     No comments   

Issue

I'm working with imagick and face some problem. I want to composite two images: image01 and image02,image01 is background image,a part of image02 composite on image01. the function just like GD's imagecopy function.

bool imagecopy( resource dst_im, resource src_im, int dst_x, int dst_y, 
                int src_x, int src_y,int src_w, int src_h )

Copy a part of src_im onto dst_im starting at the x,y coordinates src_x, src_y with a width of src_w and a height of src_h. The portion defined will be copied onto the x,y coordinates, dst_x and dst_y.

the question is: how to implement imagecopy function by Imagick?

thanks for your help.


Solution

This should do it:

//load files from source
$background = new Imagick(image01_src);
$overlay = new Imagick(image02_src);

//Crop the overlay to the required size
$overlay->cropImage ($new_width,$new_height,$x_offset,$y_offset);

//composite overlay on background
$background->compositeImage($overlay, Imagick::COMPOSITE_OVER, $margin_x, $margin_y);

//save result
$background->setImageFormat("png");
$background->writeImage(new_src);

//clean up
$background->clear();
$background->destroy();
$overlay->clear();
$overlay->destroy();


Answered By - Lukas Nagel
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I create a transparant area inside a non transparant solid color image using GD or Imagick?

 October 11, 2022     gd, imagick, php     No comments   

Issue

Using imagick and GD Library I tried to make a square image with a transparent center. I tried to do it like this :

$img = imagecreatetruecolor($width, $height); 

imagefilledrectangle($img, $left, $top, $right, $bottom, imagecolorallocate($img, 255, 255, 255)); 
imagecolortransparent($img, imagecolorallocate($img, 255, 255, 255));   

ob_start();    
ini_set('memory_limit', '-1');              
imagepng($img, './imagecolortransparent.png');
$blob = ob_get_clean();     

However the end result is always not transparent for the center small box. Am I doing this wrong somewhere? Any help will be appreciated :(.

enter image description here


Solution

You must activate imagesavealpha to get transparency.

imagesavealpha($img,true);
imagepng($img, './imagecolortransparent.png');


Answered By - Lorenz Meyer
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, October 10, 2022

[FIXED] How to make tiled image frame without using exec function?

 October 10, 2022     gd, image-processing, imagemagick, imagick, php     No comments   

Issue

Original image: Original image Here what i need: Here what i need It should be created from this small tile: It should be created from this small tile

A lot of people suggest to use ImageMagick solution (it using php exec function) - http://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=21867:

convert frame_template.gif \
-tile blackthin_top.gif -draw 'color 1,0 floodfill' -rotate 90 \
-tile blackthin_btm.gif -draw 'color 1,0 floodfill' -rotate 90 \
-tile blackthin_top.gif -draw 'color 1,0 floodfill' -rotate 90 \
-tile blackthin_btm.gif -draw 'color 1,0 floodfill' -rotate 90 \
-gravity center thumbnail.gif -composite frame_filled.gif

or

PICFrame solution (it using php exec function) - http://www.fmwconcepts.com/imagemagick/picframe/index.php:

picframe [-f frameid] [-m mattesize] [-c mattecolor] [-b bordersize] [-s shade] [-a adjust] [-o opacity ] [-d distance] infile outfile

PHP imagick has great ability to create color borders with:

$imagick = new \Imagick('image.jpg');
$imagick->scaleImage(300, 300, false);

// Create frame placeholder
$imagick->frameimage( 'red','30','30', 30, 0);

// Flood fill with color
$imagick->floodFillPaintImage('green', 10, '#6e0000',0, 0,false
);

header("Content-Type: image/jpg");
echo $imagick->getImageBlob();

But PHP imagick can't use your own image tile to create frame, only solid colors. Here is very related question - How to flood fill the frame with a pattern image using imagick php class?

Another good solution from - https://stackoverflow.com/a/28778953/2337706 but it creates image from big PNG frames and you should know correct image size.

I know that i can create it with php GD - http://php.net/manual/en/ref.image.php but i don't know correct way how implement it this way.


Solution

In ImageMagick, you could just do something simple like this:

convert a1Wit.jpg -mattecolor black -frame 10x10+3+3 -gravity west -chop 3x0 -bordercolor gold -border 3 frame_result.jpg

enter image description here

These commands should be easy enough to translate into Imagick. See http://us3.php.net/manual/en/imagick.frameimage.php and http://us3.php.net/manual/en/imagick.chopimage.php and http://us3.php.net/manual/en/imagick.borderimage.php

Or simply:

convert a1Wit.jpg -bordercolor black -border 7 -bordercolor "gray(35%)" -border 3 -bordercolor "#D0A456" -border 3 frame_result2.jpg

enter image description here

Or

convert a1Wit.jpg -mattecolor "gray(30%)" -frame 13x13+5+5 -gravity northwest -shave 5x5 -bordercolor "#D0A456" -border 3 frame_result3.jpg

enter image description here

Or

convert a1Wit.jpg -mattecolor "gray(30%)" -frame 13x13+5+5 -gravity northwest -bordercolor "#D0A456" -border 3 frame_result4.jpg

enter image description here

Adjust the color thicknesses as desired



Answered By - fmw42
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, September 19, 2022

[FIXED] How to adjust watermark according to image?

 September 19, 2022     imagemagick, imagemagick-convert, imagick, laravel, php     No comments   

Issue

I have done almost everything but i am facing one issue. I am creating multiple watermark at multiple locations. That is running fine but actually problem is when the image is having good resolution and watermark is looking very small. I want whatever the image resolution watermark should be zoom and visible here is my exec function and i am using laravel framework and i am using imagick library

$path = storage_path('app/images/TestImages/');
$mediumFileName = $path.str_random(4)."medium".str_random(4).".".$ext;
$watermarkImage = storage_path('watermark.png');
$saveWatermark = $path."image_watermark.jpg";
exec("convert $mediumFileName \( $watermarkImage -write MPR:wm \) \
-define compose:args=30,100 -compose dissolve            \
      -gravity NorthWest -geometry +3+3 -composite      \
MPR:wm -gravity NorthEast -geometry +3+3 -composite      \
MPR:wm -gravity SouthEast -geometry +3+3 -composite      \
MPR:wm -gravity Center -geometry +3+3 -composite      \
MPR:wm -gravity SouthWest -geometry +3+3 -composite $saveWatermark");

Solution

Here is a large watermark, with enough resolution for any picture as it is 1,000 pixels square.

enter image description here

Now, if we have a 1000x800 pixel image like this, we can resize the watermark to say 15% of that before compositing it (15% of 1000 is the 150 in the code):

convert image.jpg \( watermark.png -resize 150x -write MPR:wm \) \
          -gravity northwest -geometry +10+10 -composite         \
   MPR:wm -gravity northeast -geometry +10+10 -composite         \
   MPR:wm -gravity southwest -geometry +10+10 -composite         \
   MPR:wm -gravity southeast -geometry +10+10 -composite result.png

enter image description here

enter image description here

But, if we have a smaller image like this 400x300 image:

enter image description here

when we apply the watermark, we first resize it to 15% of 400, or 60:

convert image.jpg \( watermark.png -resize 60x -write MPR:wm \) \
          -gravity northwest -geometry +10+10 -composite         \
   MPR:wm -gravity northeast -geometry +10+10 -composite         \
   MPR:wm -gravity southwest -geometry +10+10 -composite         \
   MPR:wm -gravity southeast -geometry +10+10 -composite result.png

enter image description here

So, you need to get the size of your image how Andreas kindly showed you:

list($width, $height, $type, $attr) = getimagesize($mediumFileName);

and then multiply that by 0.15 (to get say 15%) and use that in your -resize parameter.


If the "aside processing" inside the parentheses above is upsetting or confusing, you can achieve the same result by loading up and resizing the watermark first, on its own, putting it into an MPR and then loading the main image and overlaying the MPR four times. It is just a different, maybe simpler, syntax:

convert watermark.png -resize 60x -write MPR:wm +delete image.jpg \
   MPR:wm -gravity northwest -geometry +10+10 -composite          \
   MPR:wm -gravity northeast -geometry +10+10 -composite          \
   MPR:wm -gravity southwest -geometry +10+10 -composite          \
   MPR:wm -gravity southeast -geometry +10+10 -composite result.png


Answered By - Mark Setchell
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get high-res thumbnails out of low-res SVGs in Mediawiki?

 September 19, 2022     imagick, librsvg, mediawiki, php, svg     No comments   

Issue

I don't exactly know how to word this question properly, so I'll make an attempt:

See the rasterized SVG on this page? Looks pretty distorted, and - excuse me language - rather s***. Now let's compare it with the one here. Both of them have the exact same SVG file and the source code is identical in wikitext. The difference is in how the rasterized "thumbnail" is generated, it seems.

The result that MediaWiki gives me

The result I get from MediaWiki.

Intended result

The intended result.

From what I have noticed - correct me if I'm wrong - both Wikipedia and Wikia either create several rasterized thumbnails for the SVG, or just simply generate them on demand, depending on the size the pages want. MediaWiki by default however, only generates one thumbnail, which is implied to have the same resolution as the original SVG - which gives us blurry and **** raster-images when rasterizing a small SVG to a large image.

Either that, or the SVGs don't get scaled/resized prior to thumbnailing/rasterization, when they should be.

Just for heads up, here's some come from my LocalSettings.php:

$wgFileExtensions = array( 'png', 'gif', 'jpg', 'jpeg',
    'xls', 'mpp', 'pdf', 'ppt', 'tiff', 'ogg', 'svg',
    'woff', 'eot', 'woff2'
);
// $wgSVGConverters['ImageMagick'] = '"' . $wgImageMagickConvertCommand . '" -background white -thumbnail $widthx$height^! $input PNG:$output';
// $wgSVGConverters['ImageMagick'] = '$path/convert -density $width -geometry $width $input PNG:$output';
$wgSVGConverters['ImageMagick'] = '$path/convert -density 1200 -background none -geometry $width $input PNG:$output';
$wgSVGConverters['rsvg'] = '/usr/bin/rsvg-convert -w $width -h $height $input -o $output';
$wgSVGConverter = 'ImageMagick';
// $wgSVGConverter = 'rsvg';
$wgSVGMaxSize = 2048;
$wgMaxImageArea = 1.25e7;
$wgMaxAnimatedGifArea = 1.0e6; 
$wgUseImageResize = true;
$wgGenerateThumbnailOnParse = true;

So... how do I enable having multiple thumbnails, if the lack of them is the cause of the problem? Is this even the cause of the problem to begin with? If not, what is the real reason why I'm not getting my intended result? What can I do?

EDIT: Already solved by switching over to ImageMagick to RSVG.


Solution

In Imagemagick, you just need to provide a large density before reading the svg file. So this works for me.

convert -density 600 The_Mystics.svg mystics.png

enter image description here



Answered By - fmw42
Answer Checked By - David Goodson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] What is difference between setImageCompressionQuality vs setCompressionQuality - Imagick

 September 19, 2022     image, image-processing, imagemagick, imagick, php     No comments   

Issue

I found two methods in Imagick for set image compression quality

A ) setImageCompressionQuality

B ) setCompressionQuality

so I want to know which one is best and why in below condition

I read that setCompressionQuality method only works for new images (?)

I am trying to compress a file jpeg/png

$im = new Imagick();

$im->readImage($file); // path/to/file
$im->setImageCompressionQuality($quality); // 90,80,70 e.g.

$im->writeImage($file);

Solution

The method setImageCompressionQuality sets compression quality for your current image. This method is a wrapper for MagickWand's MagickSetImageCompressionQuality function. Source code is:

WandExport MagickBooleanType MagickSetImageCompressionQuality(MagickWand *wand,
  const size_t quality)
{
  assert(wand != (MagickWand *) NULL);
  assert(wand->signature == MagickWandSignature);
  if (wand->debug != MagickFalse)
    (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name);
  if (wand->images == (Image *) NULL)
    ThrowWandException(WandError,"ContainsNoImages",wand->name);

  //This line sets the quality for the instance 'images'  
  wand->images->quality=quality;
  return(MagickTrue);
}

The method setCompressionQuality sets compression quality for the whole object. This method is a wrapper for MagickWand's MagickSetCompressionQuality function. Source code is:

WandExport MagickBooleanType MagickSetCompressionQuality(MagickWand *wand,
  const size_t quality)
{
  assert(wand != (MagickWand *) NULL);
  assert(wand->signature == MagickWandSignature);
  if (wand->debug != MagickFalse)
    (void) LogMagickEvent(WandEvent,GetMagickModule(),"%s",wand->name);

  //This line sets quality for the image_info struct instance.
  wand->image_info->quality=quality;
  return(MagickTrue);
}

The MagickWand struct holds instances of Image and ImageInfo structs, source:

struct _MagickWand
{
  ...

  Image
    *images;          /* The images in this wand - also the current image */

  ImageInfo
    *image_info;      /* Global settings used for images in Wand */
  ...
};

Both Image and ImageInfo structs hold a size_t quality; data member. So for your example setImageCompressionQuality is perfectly fine.



Answered By - zindarod
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How do I create a better quality image converting a .pdf to a .jpg with Imagick/PHP?

 September 19, 2022     imagick, pdf, php     No comments   

Issue

I currently have a single page PDF (http://reljac.com/so_1/all.pdf) which is a basic scan of several paper receipts. If you look at the PDF the text is clear and legible. The original is a scan of an 8.5" x 11" sheet of paper (shouldn't matter)

I've created a very simple file to convert that PDF into a .jpg using this code:

<?php     
    $im = new imagick('all.pdf[0]');
    $im->setImageFormat('jpg');
    $im->setImageCompression(imagick::COMPRESSION_LOSSLESSJPEG); 
    $im->setImageCompressionQuality(80);
    header('Content-Type: image/jpeg');
    echo $im;
?>

When I run that (http://reljac.com/so_1/pdf_jpg.php) the resulting image is illegible.

I'm working off of two servers at the moment, one tells me:

Version: ImageMagick 6.2.8 10/06/10 Q16 file:/usr/share/ImageMagick-6.2.8/doc/index.html

the other:

Version: ImageMagick 6.6.0-4 2012-05-02 Q16 http://www.imagemagick.org

Both servers create a similar quality .jpg

I've changed several of the settings including:

  • $im->setImageCompressionQuality(40);
  • $im->setImageCompressionQuality(100);
  • $im->setImageCompressionQuality(80);
  • $im->setImageCompression(imagick::COMPRESSION_JPEG); (various others from http://www.php.net/manual/en/imagick.constants.php)

I've tried adding $im->scaleImage(600,0);

Nothing seems to make anything more legible. I'd like the end result to be a legible .jpg of the original PDF - it does not have to fill the screen, it just needs to be legible. The original PDFs may be different sizes so I need to keep in mind that the source is not always 8.5" x 11".

Is there anything else I can do to enhance the quality of the resulting image or is this the best I should expect? Do I need to process these files in some other way to get a better image?

UPDATE Based on @VadimR's answer I'm now using the following:

$src = 'all.pdf';
$src_parts = pathinfo($src);

shell_exec('pdfimages ' . $src . ' ' . $src_parts['filename']);
shell_exec('convert ' . $src_parts['filename'] . '-000.pbm -resize 25% -sharpen -2 ' . $src_parts['filename'] . '.jpg');

$myImage = imagecreatefromjpeg($src_parts['filename'] . '.jpg');
header("Content-type: image/jpeg");
imagejpeg($myImage);
imagedestroy($myImage);

shell_exec('rm ' . $src_parts['filename'] . '-000.pbm');

That results in a nice, legible image.


Solution

ImageMagick delegates PDF rendering to Ghostscript, therefore for troubleshooting specify not only IM, but GS version, too, if necessary. Second, I think it's better to start with command line, and only after appropriate quality is achieved, put it into php code.

Command that gives quality (more or less):

convert -density 300 all.pdf out.jpg

Here we set rendering resolution 300 dpi. Note, it's not the same as

convert all.pdf -density 300 out.jpg

because here rendering goes at 72 dpi, then bad quality result is assigned (i.e. w/o resampling) with 300 dpi.

But, I think better approach can be to extract scans as is i.e. without transformations:

pdfimages all.pdf all

that gives all-000.pbm image -- 1-bit per sample, 3424*4400 px. I definitely can't agree, that "text is clear and legible" - some digits can only be guessed.

Then use convert command to resample and maybe try to improve e.g.

convert all-000.pbm -resize 25% -sharpen 2 out.jpg


Answered By - user2846289
Answer Checked By - Marie Seifert (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to make specified area of an image transparent with Imagick?

 September 19, 2022     imagemagick, imagick, php     No comments   

Issue

I want to make a part of an image transparent, I tried the code below, even tried many constants as COMPOSITE_DSTOUT, but all didn't work, does anyone know how to?

$fooImage->newImage(256, 256, new ImagickPixel('transparent'));
$Image->compositeImage($fooImage, Imagick::COMPOSITE_DSTOUT, $offsetX, offsetY);

I tested the code below, just got yellow with black, not transparent:

$width = 256;
$height = 256;

$image = new Imagick();
$image->newImage($width, $height, new ImagickPixel('yellow'));

$x = 50;
$y = 100;
$fooWidth = 100;
$fooHeight = 60;

//Create a new transparent image of the same size
$mask = new Imagick();
$mask->newImage($width, $height, new ImagickPixel('none'));
$mask->setImageFormat('png');

//Draw onto the new image the areas you want to be transparent in the original
$draw = new ImagickDraw();
$draw->setFillColor('black');
$draw->rectangle($x, $y, $x + $fooWidth, $y + $fooHeight);
$mask->drawImage($draw);

//Composite the images
$image->compositeImage($mask, Imagick::COMPOSITE_DSTOUT, 0, 0,
    Imagick::CHANNEL_ALPHA);

$image->setImageFormat('png');
$image->writeImage($path);

Got black inside yellow, not transparent in yellow

result image


Solution

You need to make a black and white mask image the size of your input (white where you want it to be opaque and black where you want it to be transparent). Then use the equivalent of -compose copyopacity -composite to put the mask into the alpha channel of the image. Sorry, I do not code Imagick.

Here is an example using ImageMagick command line syntax:

Input:

enter image description here

convert logo.jpg \( -size 640x480 xc:white -size 200x200 xc:black -geometry +200+100 -compose over -composite \) +geometry -alpha off -compose copy_opacity -composite result.png

enter image description here

You can see it is transparent by compositing it over another image (in this case a checkerboard).

convert ( -size 640x480 pattern:checkerboard ) result.png -compose over -composite result2.jpg

enter image description here



Answered By - fmw42
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to translate ImageMagick command to Imagick in PHP?

 September 19, 2022     imagemagick, imagick, php     No comments   

Issue

I've tried to translate it, but doesn't work, doesn't anyone know what the wrong is ?

ImageMagick

convert source.jpg \( -size 640x480 xc:white -size 200x200 
xc:black -geometry +200+100 -compose over -composite \) 
+geometry -alpha off -compose copy_opacity -composite result.png

PHP code with Imagick I tried, but didn't work:

//Open your image and get its dimensions
$image = new Imagick('source.png');
$height = $image->getImageHeight();
$width = $image->getImageWidth();

//Create a new transparent image of the same size
$mask = new Imagick();
$mask->newImage($width, $height, new ImagickPixel('white'));

//Draw onto the new image the areas you want to be transparent in the original
$draw = new ImagickDraw();
$draw->setFillColor('black'); 
$draw->rectangle($x, $y, $x + 200, $y + 200);
$mask->drawImage( $draw );

//Composite the images
$image->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0, Imagick::CHANNEL_ALPHA);
$image->setImageFormat('png');
$image->writeImage("~/images/result.png");

Original Question:

How to make specified area of an image transparent with Imagick?

Another trying

$width = 256;
$height = 256;
$x = 50;
$y = 100;
$fooWidth = 100;
$fooHeight = 60;


$image = new Imagick();
$image->newImage($width, $height, new ImagickPixel('yellow'));


//Create a new transparent image of the same size
$mask = new Imagick();
$mask->newImage($width, $height, new ImagickPixel('white'));
$mask->setImageFormat('png');

//Draw onto the new image the areas you want to be transparent in the original
$draw = new ImagickDraw();
$draw->setFillColor('black');
$draw->rectangle($x, $y, $x + $fooWidth, $y + $fooHeight);
$mask->drawImage($draw);

//Composite the images
$image->compositeImage($mask, Imagick::COMPOSITE_COPYOPACITY, 0, 0);

$image->setImageFormat('png');
$image->writeImage($path);

COMPOSITE_COPYOPACITY looks doesn't work:

enter image description here


Solution

try turning alpha off at the end when you create the mask. This works fine for me:

convert -size 500x500 xc:yellow \( -size 500x500 xc:white -fill black -draw "rectangle 100,100 300,300" -alpha off \) -compose copy_opacity -composite result.png

enter image description here

See http://us3.php.net/manual/en/imagick.setimagematte.php where the example adds

$mask->setImageMatte(false);

After the draw command and before the compositeImage() command



Answered By - fmw42
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] how to make images look like a canvas or a toile with php imagick library

 September 19, 2022     image-manipulation, imagemagick, imagick, php     No comments   

Issue

I'm using php Imagick library for some image manipulation. I can distort the perspective of images but can not make them look like a canvas or a toile

>>

It would be great if someone could explain me how can I do that.

Thanks in advance


Solution

I think I managed to do what I wanted.

Here is my approach

$im = new Imagick('Desert.jpg');
$im->setImageFormat('png');


$d = $im->getImageGeometry();
$w = $d['width'];  
$h = $d['height']; 

$im3 = new Imagick();
$im3->newImage(1, $h, 'none','png');
$im3->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);

$im1 = $im->clone();;
$im1->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
$im1->setImageMatte(true);
$im1->cropImage(($w-10), $h, 0, 0);
$controlPoints = array(
                    0,0, 15,15, 
                    ($w-10),0, ($w-10),0, 
                    0,$h, 25,($h-20), 
                    ($w-10),$h, ($w-10),$h 
                    );

$im1->distortImage(Imagick::DISTORTION_BILINEAR, $controlPoints, true);

$im2 = $im->clone();
$im2->setImageVirtualPixelMethod(Imagick::VIRTUALPIXELMETHOD_TRANSPARENT);
$im2->setImageMatte(true);

$im2->cropImage(10, $h, ($w-10), 0);


$controlPoints2 = array(
                    0,0, 0,0, 
                    10,0,10,10, 
                    0,$h, 0,$h,
                    10,$h, 10,($h-10) 
                    );

$im2->distortImage(Imagick::DISTORTION_BILINEAR, $controlPoints2, true); 

$image = new Imagick();

$image->addImage($im1);
$image->addImage($im3);
$image->addImage($im2);
$image->resetIterator();

$combined = $image->appendImages(false);

$shadow = $combined->clone(); 

$shadow->setImageBackgroundColor( new ImagickPixel( 'black' ) ); 

$shadow->shadowImage( 50, 3, 5, 5 ); 

$shadow->compositeImage( $combined, Imagick::COMPOSITE_OVER, 0, 0 ); 

$shadow->writeImage('Desert_Distorded.png');

and the final result is

https://i.stack.imgur.com/DFj6R.png



Answered By - Onur Kucukkece
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to create a large (High Quality 300dpi) image from JSON / array of Data (width,height,x,y,angels) using PHP ImageMagic / Imagick

 September 19, 2022     imagemagick, imagick, math, php, rotation     No comments   

Issue

I created a design (270x470) with some pictures and text on Canvas using FabricJs then i export all pictures/text information in JSON format by fabricJS's canvas.toJSON() method And Now i need to Re-Draw that design on a High Quality (2790x4560) image in PHP using Imagick.

FabricJS Design

JSON dataArray for above design which contains all object's information like size,position,angle etc..

{
"width": "2790",
"height": "4560",
"json_data": {
    "objects": [{
            "type": "image",
            "originX": "left",
            "originY": "top",
            "left": "5",
            "top": "105",
            "width": "260",
            "height": "260",
            "scaleX": "1",
            "scaleY": "1",
            "angle": "0",
            "opacity": "1",
            "src": "http:\\example.com/images/098f20be9fb7b66d00cb573acc771e99.JPG",
        }, {
            "type": "image",
            "originX": "left",
            "originY": "top",
            "left": "5",
            "top": "229.5",
            "width": "260",
            "height": "11",
            "scaleX": "1",
            "scaleY": "1",
            "angle": "0",
            "opacity": "1",
            "src": "http:\\example.com/images/aeced466089d875a7c0dc2467d179e58.png",
        }, {
            "type": "image",
            "originX": "left",
            "originY": "top",
            "left": "51.07",
            "top": "135.58",
            "width": "260",
            "height": "11",
            "scaleX": "1",
            "scaleY": "1",
            "angle": "47.41",
            "opacity": "1",
            "src": "http:\\example.com/images/910ce024d984b6419d708354bf3641a3.png",
        }, {
            "type": "image",
            "originX": "left",
            "originY": "top",
            "left": "139.71",
            "top": "104.97",
            "width": "260",
            "height": "11",
            "scaleX": "1",
            "scaleY": "1",
            "angle": "89.65",
            "opacity": "1",
            "src": "http:\\example.com/images/88e096a82e5f8a503a71233addaff64c.png",
        }, {
            "type": "image",
            "originX": "left",
            "originY": "top",
            "left": "230.78",
            "top": "146.93",
            "width": "260",
            "height": "11",
            "scaleX": "1",
            "scaleY": "1",
            "angle": "134.98",
            "src": "http:\\example.com/images/d2c0ec738c1fec827381cfeb600bd87d.png",
        }, {
            "type": "image",
            "originX": "left",
            "originY": "top",
            "left": "265.01",
            "top": "240.19",
            "width": "260",
            "height": "11",
            "scaleX": "1",
            "scaleY": "1",
            "angle": "179.86",
            "opacity": "1",
            "src": "http:\\example.com/images/3f0bc771261860d917e0ad6d09cb2064.png",
        }],
    "background": "#FF00FF"
}}

And here my Code Snippet for generating High Quality Image in PHP using JSON dataArray

error_reporting(E_ALL | E_STRICT);

try {
  $id = $_GET['id']; // Design ID

  define('DS', DIRECTORY_SEPARATOR);

  $jsonDir = dirname(__FILE__) . DS . 'media' . DS . 'designs';
  $printData = json_decode(file_get_contents($jsonDir . DS . $id . '.json'));

  } catch (Exception $e) {
     echo $e->getMessage();
  }

try {
   $print = new Imagick();
   $print->setResolution(300, 300);
   $background = (empty($printData->json_data->background)) ? 'transparent' : $printData->json_data->background;
   $print->newImage($printData->width, $printData->height, new ImagickPixel($background));

   $print->setImageFormat('png32');
   $print->setImageUnits(imagick::RESOLUTION_PIXELSPERCENTIMETER);
} catch (Exception $e) {
   echo $e->getMessage();
}

// Re-Scaling each Image/Text for Larger Canvas/Image 
foreach ($printData->json_data->objects as $i => $object) {

   if ($object->type == 'image') {
        addImage($object, $print, $printData);
   } else {
        addText($object, $print, $printData);
   }
}


try {
   // Saving High Quality Image in (300 dpi)
   $fileDir = dirname(__FILE__) . DS . 'media' . DS . 'prints';

   if (!file_exists($fileDir) || !is_dir($fileDir)) {
       if (!mkdir($fileDir))
           die("Could not create directory: {$fileDir}\n");
   }
   $saved = $print->writeimage($fileDir . DS . $id . '.png');
   header('Content-type: image/png');
   echo $print;
 } catch (Exception $e) {
      echo $e->getMessage();
 }

addImage();

function addImage($object, $print, $printData) {

    try {
        $widthScale = ($printData->width / 270);
        $heightScale = ($printData->height / 470);
        $fileDir = dirname(__FILE__) . DS . 'media' . DS . 'original' . DS;
        $src = new Imagick($fileDir . basename($object->src));

        $size = $src->getImageGeometry();

        $resizeWidth = ($object->width * $object->scaleX) * $widthScale;
        $resizeHeight = ($object->height * $object->scaleY) * $heightScale;
        $src->resizeImage($resizeWidth, $resizeHeight, Imagick::FILTER_LANCZOS, 1);
        $sizeAfterResize = $src->getImageGeometry();

        $src->rotateImage(new ImagickPixel('none'), $object->angle);
        $sizeAfterRotate = $src->getImageGeometry();


        if (!$object->angle) {
            $left = $object->left * $widthScale;
            $top = $object->top * $heightScale;
        } else {

            switch ($object->angle) {
                case $object->angle > 315:
                    $left = ($object->left * $widthScale);
                    $top = ($object->top * $heightScale);
                    break;
                case $object->angle > 270:
                    $left = ($object->left * $widthScale);
                    $top = ($object->top * $heightScale);

                    break;
                case $object->angle > 225:
                    $left = ($object->left * $widthScale);
                    $top = ($object->top * $heightScale);
                    break;
                case $object->angle > 180:
                    $left = ($object->left * $widthScale);
                    $top = ($object->top * $heightScale);
                    break;
                case $object->angle > 135:
                    $left = ($object->left * $widthScale);
                    $top = ($object->top * $heightScale);
                    break;
                case $object->angle > 90:
                    $left = ($object->left * $heightScale) - ($sizeAfterRotate['width'] / 2);
                    $top = ($object->top * $heightScale) - ($sizeAfterRotate['width'] / 2);
                    break;
                case $object->angle > 45:
                    $left = ($object->left * $widthScale) - $size['height'] * $widthScale;
                    $top = ($object->top * $heightScale) - $size['height'] * $heightScale;
                    break;

                default:
                    $left = $object->left * $widthScale;
                    $top = $object->top * $heightScale;

                    break;
            }
        }

        $print->compositeImage($src, Imagick::COMPOSITE_DEFAULT, $left, $top);
    } catch (Exception $e) {
        echo $e->getMessage();
    }
}

My Output results (90%) is there with above solution, but as we can see some image (blue number line) doesn't place at exact position which should look like first design image

Imagick Design

Basically what i am trying to do is, " Inside a Loop calling an addImage Method for scale - rotate - position each image on Print Image(300DPi)

i am not sure what i am missing to get exact offset (new x,y coordinates/position/Left-Top ) after Rotation for an image in Imagick or i am Rotating object after Scale then compose

or May be A Math Formula like Math.PI :)

Question is: How Can i Calculate New offset/Position according to Rotation Degree/Angle after Scale ?

I hope posted snippet are useful for everyone.


Solution

Here I get a solution, may be it will help others like for me

<?php

// AZinkey
ini_set('memory_limit', '1024M'); // may be need increase memory size
ini_set('display_errors', 1); // enable error display
error_reporting(E_ALL); // show all type errors

$id = $_GET['id'];
$file = $id . ".json"; // json file e.g. 1234.json
$printData = json_decode(file_get_contents($file));

$mask = "mask.png"; // a image (4395x4395) which contains 2669x4395 black fill in center
$maskImg = new Imagick($mask);
$d = $maskImg->getImageGeometry();

$maskWidth = $d['width'];
$maskHeight = $d['height'];

// Then reduce any list of integer
$cd = array_reduce(array($maskWidth, 400), 'gcd');
$r1 = $maskWidth / $cd;
$r2 = 400 / $cd;

$newPrintData['r1'] = $r1;
$newPrintData['r2'] = $r2;


try {
    $print = new Imagick();
    $print->setResolution(300, 300);
    $background = (empty($printData->json_data->background)) ? 'transparent' : $printData->json_data->background;
    $print->newImage($maskWidth, $maskHeight, new ImagickPixel($background));

    $print->setImageMatte(TRUE);
    $print->setImageFormat('png32');
    $print->setImageUnits(imagick::RESOLUTION_PIXELSPERCENTIMETER);
} catch (Exception $e) {
    echo $e->getMessage();
}

// create two array for store text & images information separately 
$imageObjects = $textObjects = [];

foreach ($printData->json_data->objects as $object) {
    if ($object->type == 'image') {
        $imageObjects[] = $object;
    } else if ($object->type == 'text') {
        $imageObjects[] = $object;
    }
}
foreach ($imageObjects as $object) {
    addImageToLarge($object, $print, $printData, $newPrintData);
}

foreach ($imageObjects as $object) {
    addTextToLarge($object, $print, $printData, $newPrintData);
}
try {
    $print->setImageFormat('png');
    $saveFile = $id . "_print.json"; // save large image _print.png
    file_put_contents($saveFile, $print);
} catch (Exception $e) {
    echo $e->getMessage();
    exit();
}

function addImageToLarge($object, $print, $printData, $newPrintData) {
    try {
        $src = new Imagick($object->src);
        $size = $src->getImageGeometry();
        $resizeWidth = changeDpi(scale($object->width, $newPrintData['r1'], $newPrintData['r2']) * $object->scaleX);
        $resizeHeight = changeDpi(scale($object->height, $newPrintData['r1'], $newPrintData['r2']) * $object->scaleY);

        $src->resizeImage($resizeWidth, $resizeHeight, Imagick::FILTER_LANCZOS, 1);
        $sizeAfterResize = $src->getImageGeometry();

        $src->rotateImage(new ImagickPixel('none'), $object->angle);
        $sizeAfterRotate = $src->getImageGeometry();

        $left = $object->left < 0 ? -1 * abs(changeDpi(scale($object->left, $newPrintData['r1'], $newPrintData['r2']))) : changeDpi(scale($object->left, $newPrintData['r1'], $newPrintData['r2']));
        $top = $object->top < 0 ? -1 * abs(changeDpi(scale($object->top, $newPrintData['r1'], $newPrintData['r2']))) : changeDpi(scale($object->top, $newPrintData['r1'], $newPrintData['r2']));

        $print->compositeImage($src, Imagick::COMPOSITE_OVER, $left, $top);
    } catch (Exception $e) {
        echo $e->getMessage();
        exit();
    }
}

function addTextToLarge($object, $print, $printData, $newPrintData) {
    $fnt['Times New Roman'] = "font/times_6.ttf";
    $fnt['Arial'] = "font/arial_8.ttf";
    $fnt['Arial Black'] = "font/ariblk_8.ttf";
    $fnt['Comic Sans MS'] = "font/comic_5.ttf";
    $fnt['Courier New'] = "font/cour_5.ttf";
    $fnt['Georgia'] = "font/georgia_5.ttf";
    $fnt['Impact'] = "font/impact_7.ttf";
    $fnt['Lucida Console'] = "font/lucon_3.ttf";
    $fnt['Lucida Sans Unicode'] = "font/l_4.ttf";
    $fnt['Palatino Linotype'] = "font/pala_7.ttf";
    $fnt['Tahoma'] = "font/tahoma_3.ttf";
    $fnt['Trebuchet MS'] = "font/trebuc_3.ttf";
    $fnt['Verdana'] = "font/verdana_5.ttf";

    try {
        $line_height_ratio = $object->lineHeight;
        $resizeWidth = changeDpi(scale($object->width, $newPrintData['r1'], $newPrintData['r2']) * $object->scaleX);
        $resizeHeight = changeDpi(scale($object->height, $newPrintData['r1'], $newPrintData['r2']) * $object->scaleY);

        $print2 = new Imagick();
        $print2->setResolution(300, 300);
        $print2->newImage($resizeWidth, $resizeHeight, "transparent");
        $print2->setImageVirtualPixelMethod(imagick::VIRTUALPIXELMETHOD_BACKGROUND);
        $print2->setImageFormat('png32');
        $print2->setImageUnits(imagick::RESOLUTION_PIXELSPERCENTIMETER);

        // Instantiate Imagick utility objects
        $draw = new ImagickDraw();
        $color = new ImagickPixel($object->fill);

        //$starting_font_size = 100*1.33;
        $font_size = (($object->fontSize * $resizeWidth) / $object->width);

        $draw->setFontWeight(($object->fontWeight == 'bold') ? 600 : 100 );
        $draw->setFontStyle(0);
        $draw->setFillColor($color);

        // Load Font 
        //$font_size = $starting_font_size;
        $draw->setFont($fnt[$object->fontFamily]);
        $draw->setFontSize($font_size);

        $draw->setTextAntialias(true);
        $draw->setGravity(Imagick::GRAVITY_CENTER);

        if ($object->stroke) {
            $draw->setStrokeColor($object->stroke);
            $draw->setStrokeWidth($object->strokeWidth);
            $draw->setStrokeAntialias(true);  //try with and without
        }

        $total_height = 0;

        // Run until we find a font size that doesn't exceed $max_height in pixels
        while (0 == $total_height || $total_height > $resizeHeight) {
            if ($total_height > 0) {
                $font_size--; // we're still over height, decrement font size and try again
            }
            $draw->setFontSize($font_size);

            // Calculate number of lines / line height
            // Props users Sarke / BMiner: http://stackoverflow.com/questions/5746537/how-can-i-wrap-text-using-imagick-in-php-so-that-it-is-drawn-as-multiline-text
            $words = preg_split('%\s%', $object->text, -1, PREG_SPLIT_NO_EMPTY);
            $lines = array();
            $i = 0;
            $line_height = 0;

            while (count($words) > 0) {
                $metrics = $print2->queryFontMetrics($draw, implode(' ', array_slice($words, 0, ++$i)));
                $line_height = max($metrics['textHeight'], $line_height);

                if ($metrics['textWidth'] > $resizeWidth || count($words) < $i) {
                    $lines[] = implode(' ', array_slice($words, 0, --$i));
                    $words = array_slice($words, $i);
                    $i = 0;
                }
            }

            $total_height = count($lines) * $line_height * $line_height_ratio;

            if ($total_height > 0) {

            }
        }
        // Writes text to image
        $x_pos = 0;
        $y_pos = 0;

        for ($i = 0; $i < count($lines); $i++) {
            $print2->annotateImage($draw, $x_pos, $y_pos + ($i * $line_height * $line_height_ratio), $object->angle, $lines[$i]);
        }

        if ($object->flipX == 1)
            $print2->flopImage(); // x
        if ($object->flipY == 1)
            $print2->flipImage(); // y

        $print2->trimImage(0);
        $print2->setImagePage(0, 0, 0, 0);

        $print2->resizeImage($resizeWidth, 0, Imagick::FILTER_CATROM, 0.9, false);

        $left = $object->left < 0 ? -1 * abs(changeDpi(scale($object->left, $newPrintData['r1'], $newPrintData['r2']))) : changeDpi(scale($object->left, $newPrintData['r1'], $newPrintData['r2']));
        $top = $object->top < 0 ? -1 * abs(changeDpi(scale($object->top, $newPrintData['r1'], $newPrintData['r2']))) : changeDpi(scale($object->top, $newPrintData['r1'], $newPrintData['r2']));

        $print->compositeImage($print2, Imagick::COMPOSITE_OVER, $left, $top);

        //header("Content-Type: image/png");
        //echo $print2;exit;
    } catch (Exception $e) {
        echo $e->getMessage();
        exit();
    }
}

//The greatest common divisor (GCD) 
function gcd($a, $b) {
    return $b ? gcd($b, $a % $b) : $a;
}

function changeDpi($px) {
    //return ($px/96)*300;
    return $px;
}

function scale($px, $r1, $r2) {
    return $px * $r1 / $r2;
}


Answered By - AZinkey
Answer Checked By - David Marino (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to overlay transparent text with background on picture?

 September 19, 2022     imagemagick, imagemagick-convert, imagick     No comments   

Issue

I have a background picture. Now I want to draw a rounded rectangle with a text shaped hole on it. Do I have to draw a mask pic first?


Update: I want the picture show through the text, but not the rounded rectangle. My convert command version is 6.9.7, on Linux.


Solution

Sorry, I am still not sure I understand what you want for the round rectangle. But here is one method that computes a white round rectangle, puts transparent text in it, then overlays that on the lena background image.

convert \( -size 150x150 xc:white \) \
\( +clone  -alpha extract \
-draw 'fill black polygon 0,0 0,15 15,0 fill white circle 15,15 15,0' \
\( +clone -flip \) -compose Multiply -composite \
\( +clone -flop \) -compose Multiply -composite \
\) -alpha off -compose CopyOpacity -composite \
\( -size 100x100 -background none -fill white -gravity center \
-pointsize 36 -font arial label:"TEST"  \) \
-gravity center -compose dstout -composite -alpha on \
lena.png +swap -compose over -composite tmp.png

enter image description here



Answered By - fmw42
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to identify if an image have an embed sRGB icc profile?

 September 19, 2022     color-management, color-profile, image, imagemagick, imagick     No comments   

Issue

I would like to remove from my images their sRGB profile if they have one. the problem i don't know how to identify that an image have a sRGB profile. What the good way to do ?


Solution

In Imagemagick, use

convert image.suffix -format "%[profiles]\n" info:

or

convert image.suffix -format "%[profile:icc]\n" info:

unless your Imagemagick version is ancient.

For example:

convert logo.jpg  -format "%[profiles]\n" info:
icc


convert logo.jpg  -format "%[profile:icc]\n" info:
sRGB built-in


Answered By - fmw42
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I draw a dashed line in PHP ImageMagick?

 September 19, 2022     drawing, imagick, php     No comments   

Issue

I'm trying to draw a dashed line using PHP Imagick. This code produces a solid line:

$line = new ImagickDraw();
$line->setStrokeWidth(3);
$line->setStrokeDashArray([10, 10]);
$line->line(0, 0, 100, 100);

setStrokeDashArray() seems to work for outlines on ImagickDraw::rectangle() but not ImagickDraw::line() drawings. Is there any way to draw simple dashed lines?


Solution

To get a nice dashed line without a solid line inside of it, set the fill color to opacity of zero (the actual color choice doesn't matter so long as the opacity value is a 0), and then don't forget to set a stroke color.

A working example (with an added debugging to browser dump):

$line = new ImagickDraw();
$line->setStrokeColor('rgb(0, 0, 0)');
$line->setFillColor('rgba(255, 255, 255, 0)');
$line->setStrokeWidth(3);
$line->setStrokeDashArray([10, 10]);
$line->line(0, 0, 100, 100);

// for debugging, output to browser:
$image = new Imagick();
$image->newImage(200, 200, 'rgb(230, 230, 230)');
$image->setImageFormat("png");
$image->drawImage($line);
header("Content-Type: image/png");
echo $image->getImageBlob();
exit;

Debug output result:

Debug Output Example



Answered By - IncredibleHat
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to set up a cron job for ffmpeg in centOS 6

 September 19, 2022     cron, ffmpeg, imagick, linux, php     No comments   

This summary is not available. Please click here to view the post.
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How can I loop imagick to show preview images of all pdf files in a folder

 September 19, 2022     imagick, php     No comments   

Issue

I have this code:

$im = new imagick($folder) . '[0]');
// convert to JPEG
$im->setImageFormat('jpg');
$im->resizeImage(290, 375, imagick::FILTER_LANCZOS, 1);
$im->setResolution( 700, 700 );
header('Content-Type: image/jpeg');
echo $im;

My question is: How do I loop this result? Any time I loop, I get header issue.


Solution

I was able to solve it. I used this method: In my loop, I called thumbnail.php as image source

<li><a href='download.php?pathname=$file'><img src='thumbnail.php?pathname=$file' style='float:left; margin-top:-10px; text-align:center; width:111px;' /></li>

Then on thumbnail.php I call my header and imagick, this way:

header('Content-Type: image/jpeg');

$im = new imagick($_GET['pathname']. '[0]');
// convert to JPEG
$im->setImageFormat('jpg');
$im->resizeImage(290, 375, imagick::FILTER_LANCZOS, 1);
$im->setResolution( 700, 700 );

echo $im;

Worked the way I like it!



Answered By - Sam Adah
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Which Programming Language have a best image filter?

 September 19, 2022     image-effects, imagick, opencv, photo     No comments   

Issue

Which programming language has best possible image filter and also provide art photo effect and oil paint effect. I've also tried in php-imagick, python-opencv, css, and javascript but they do not exactly provide art effect and oil paint effect.

Prisma app also provide art and oil paint effect but they use neural network and ai technology so how can I use this both technology for my project.


Solution

As you have mentioned php-imagick and python-opencv, what you need is a library that provides you the tools you want, the programming language is irrelevant.

Have a look at G'MIC and the image gallery.



Answered By - Catree
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to store data in an image with php?

 September 19, 2022     image-processing, imagick, php     No comments   

Issue

I have tried to use the imagick library to create two functions like this:

function storeCoordinatesImage($img_path, $coordinates){
    $im = new imagick($img_path);
    $im->setImageProperty("coords", $coordinates);
    $im->writeImage($img_path);
}

function getCoordinatesImage($img_path){
    $im = new imagick($img_path);
    return $im->getImageProperty("coords");
}

If I run:

if(!storeCoordinatesImage("I.jpg", "hi")) echo "fal";
echo getCoordinatesImage("I.jpg");

Nothing is returned.

But if I run:

$im = new imagick($img_path);
$im->setImageProperty("coords", "hello");
echo $im->getImageProperty("coords");

it returns "hello".

So it must be some issue with writing to the image? Although none of these functions are returning false. (i.e they are all working)


Solution

As Ben mentioned this is not possible. Instead you can add a "comment":

function storeCommentImage($img_path, $coordinates){
    $im = new imagick($img_path);
    $im->commentImage($coordinates);
    return $im->writeImage($img_path);
}

function getCommentImage($img_path){
    $im = new imagick($img_path);
    return $im->getImageProperty("comment");
}


Answered By - maxisme
Answer Checked By - Marilyn (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to set up phpimagik in Mac OS X?

 September 19, 2022     imagick, macos     No comments   

Issue

Can anyone tell me simple step by step to set up phpimagick in OS X?


Solution

Yes, use homebrew. Go to the homebrew website and install it with the one line script there. - I don't want to paste it here because you need the latest and greatest line at the time of following these instructions.

Then, when you have homebrew installed, do these steps to get ImageMagick installed and running under PHP and also with Apache.

# Check all of homebrew is working - fix any errors before proceeding
brew doctor

# Get latest versions of everything if you already had "homebrew" installed
# Probably not necessary if you just installed "homebrew" in previous step
brew update && brew upgrade

# Find latest PHP version - using "brew search"
newestPHP=$(brew search php | grep -E "php[0-9]+$" | sort | tail -1)
echo $newestPHP

e.g. php56

# Install latest PHP and corresponding ImageMagick
brew install ${newestPHP} ${newestPHP}-imagick

e.g. brew install php56 php56-imagick

# Check that the installation worked - you MUST use "/usr/local/bin/php"
/usr/local/bin/php -i | grep -i imag

Output

Additional .ini files parsed => /usr/local/etc/php/5.6/conf.d/ext-imagick.ini
PHP Warning:  Unknown: It is not safe to rely on the system's timezone settings. You are *required* to use the date.timezone setting or the date_default_timezone_set() function. In case you used any of those methods and you are still getting this warning, you most likely misspelled the timezone identifier. We selected the timezone 'UTC' for now, but please set date.timezone to select your timezone. in Unknown on line 0
imagick
imagick module => enabled
imagick module version => 3.1.2
imagick classes => Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator
ImageMagick version => ImageMagick 6.9.1-1 Q16 x86_64 2015-04-15 http://www.imagemagick.org
ImageMagick copyright => Copyright (C) 1999-2015 ImageMagick Studio LLC
ImageMagick release date => 2015-04-15
ImageMagick number of supported formats:  => 204
ImageMagick supported formats => 3FR, AAI, AI, ART, ARW, AVI, AVS, BGR, BGRA, BGRO, BMP, BMP2, BMP3, BRF, CAL, CALS, CANVAS, CAPTION, CIN, CIP, CLIP, CMYK, CMYKA, CR2, CRW, CUR, CUT, DCM, DCR, DCX, DDS, DFONT, DNG, DOT, DPX, DXT1, DXT5, EPDF, EPI, EPS, EPS2, EPS3, EPSF, EPSI, ERF, FAX, FITS, FRACTAL, FTS, G3, GIF, GIF87, GRADIENT, GRAY, GV, HALD, HDR, HISTOGRAM, HRZ, HTM, HTML, ICB, ICO, ICON, IIQ, INFO, INLINE, IPL, ISOBRL, JNG, JNX, JPE, JPEG, JPG, JPS, JSON, K25, KDC, LABEL, M2V, M4V, MAC, MAP, MASK, MAT, MATTE, MEF, MIFF, MKV, MNG, MONO, MOV, MP4, MPC, MPEG, MPG, MRW, MSL, MSVG, MTV, MVG, NEF, NRW, NULL, ORF, OTB, OTF, PAL, PALM, PAM, PANGO, PATTERN, PBM, PCD, PCDS, PCL, PCT, PCX, PDB, PDF, PDFA, PEF, PES, PFA, PFB, PFM, PGM, PICON, PICT, PIX, PJPEG, PLASMA, PNG, PNG00, PNG24, PNG32, PNG48, PNG64, PNG8, PNM, PPM, PREVIEW, PS, PS2, PS3, PSB, PSD, PWP, RADIAL-GRADIENT, RAF, RAS, RAW, RGB, RGBA, RGBO, RGF, RLA, RLE, RMF, RW2, SCR, SCT, SFW, SGI, SHTML, SIX, SIXEL, SPARSE-COLOR, SR2, SRF, STEGANO, SUN, SVG, SVGZ, TEXT, TGA, THUMBNAIL, TILE, TIM, TTC, TTF, TXT, UBRL, UIL, UYVY, VDA, VICAR, VID, VIFF, VIPS, VST, WBMP, WMV, WPG, X3F, XBM, XC, XCF, XPM, XPS, XV, YCbCr, YCbCrA, YUV
imagick.locale_fix => 0 => 0
imagick.progress_monitor => 0 => 0

That completes the installation if you only want to run ImageMagick under PHP outside your website.

The remaining steps are only necessary if you want to run PHP and ImageMagick under Apache inside your website.

# Check if PHP module loaded in Apache config file - /etc/apache2/httpd.conf
grep "^LoadModule.*php5_module.*libphp.*" /etc/apache2/httpd.conf
Check it matches, or if not present add a line like this
LoadModule php5_module /usr/local/Cellar/php56/5.6.6/libexec/apache2/libphp5.so

# Restart Apache
sudo apachectl restart


Answered By - Mark Setchell
Answer Checked By - Cary Denson (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] How to get image blob from ImageMagick convert command in php

 September 19, 2022     imagemagick, imagemagick-convert, imagick, php     No comments   

Issue

It is possible to get a binary blob by using ImageMagick convert via PHP's shell_exec(). It's very difficult to convert such a command to PHP Imagick class. Is there any alternative way to implement this feature?

I am using Imagick like this.

$im = new Imagick('some image');
$im->trimImage(20000);
header ("Content-Type: image/{$im->getImageFormat()}");
echo $im->getImageBlob(); // need output in from of blob

I want do get output result similar to this.

convert imageName.png -alpha set -   white -border 1 -fill none -fuzz 3% -draw "color 0,0 floodfill" -shave 1x1 removed_edges.png

If ImageMagick command returns a binary blob instead of writing to a file, my problems will be solved.


Solution

Appended jpg:- after command instead of image name & it's working.

$command = "convert imageName.png -alpha set - white -border 1 -fill none -fuzz 3% -draw "color 0,0 floodfill" -shave 1x1 jpg:-"; header ("Content-Type: image/jpg"); echo shell_exec($command);



Answered By - Sumeet Roy
Answer Checked By - Candace Johnson (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing