-
LINUX > imagemagick
- It resizes the image to five times the output size using the -sample function, which has its own built-in resampling filter that’s similar to the nearest-neighbor approach discussed above.
- It resizes the image to its final output size using the basic -resize filter.
- It strips meta data from the image.
INSTALLATION
1 -
wget ftp://ftp.imagemagick.org/pub/ImageMagick/ImageMagick.tar.gz2 -
tar xvfz ImageMagick.tar.gz3 -
cd ImageMagick-x.x.x4 -
./configure5 -
make6 - Si aucune erreur,
make installSi erreur "convert: no decode delegate for this image format JPEG"
Il n’existe pas de librairie pour décoder le format JPEG.
1 - Aller à http://www.imagemagick.org/download/delegates/ et chercher un fichier tar.gz qui soit en rapport avec JPEG.
Par exemple, j’ai trouvé ceci : jpegsrc.v9b.tar.gz.
2 - Copier l’adresse trouvée puis :
wget http://www.imagemagick.org/download/delegates/jpegsrc.v9b.tar.gz3 - Execute "gunzip libjpeg-6b.tar.gz"
4 - Execute "tar -xvf libjpeg-6b.tar"
5 - Change directories to the newly created "libjpeg-x"
6 - Execute "./configure"
7 - Execute "make"
8 - Execute "make test"
9 - Execute "make -n install" first to see if the makefile will put the files where you want them.
10 - If there are no errors and you’re ok with the installation path go ahead and install with "make install"
11 - Et surtout, recommencer toute la séquence d’installation de imagemagick
PIXELISER
convert -resize 10% image.jpg newimage.jpg convert -resize 1000% newimage.jpg newimage.jpg
convert rose: -interpolate nearest -virtual-pixel mirror -spread 5 spread_rose.png
convert -scale 10% -scale 1000% original.jpg pixelated.jpg
EFFET PEINTURE
The "-paint" operator is designed to convert pictures into paintings made by applying thick ‘blobs’ of paint to a canvas. The result is a merging of neighbourhood colors into larger single color areas.
convert rose: -paint 1 rose_paint_1.gif convert rose: -paint 3 rose_paint_3.gif convert rose: -paint 5 rose_paint_5.gif convert rose: -paint 10 rose_paint_10.gif convert rose: -blur 0x3 -paint 10 rose_blur_paint_10.gif
NOTE : at a high radius for the paint blobs, the blobs start to get a squarish look to them. This effect can be smoothed somewhat by blurring the image slightly before hand, as shown in the last image above. It is an interesting effect and could be used to make some weird and wonderful background images. For example see its use in Background Examples. On final warning. While "-paint" is supposed to produce areas of a single solid color, at large radius values, it has a tendency to produce a vertical gradient in some areas. This is most annoying, and may be a bug. Does anyone know? There are alternative to using "-paint". One is to use "-statistic Mode" instead, which assigns each pixel with the ‘predominate color’ within the given rectangular neighbourhood, and can produce a nicer result.
convert rose: -statistic Mode 10 rose_paint_mode.gifAnother is to use some of the Morphology Methods, and more specifically the Intensity Varient for Color Images. Here for example is an ‘OpenIntensity’ Morphology on the rose.
convert rose: -morphology OpenI Disk rose_paint_open.gifAnd here I use ‘CloseIntensity’ with a slightly smaller ‘Disk’.
convert rose: -morphology CloseI Disk:2.5 rose_paint_close.gifPixelate an Image
Both techniques involve shrinking the image (to generate fewer pixels), then enlarging them in such a way so as to create ‘pixel block’ using either a Scaling Operator or Sampling Operator to generate the block of color.
It is just how the image is reduced that determines exactly what color wil be used. A single pixel sample, or a merged average color.
convert rose: -sample 25% -scale 70×46\! rose_pixelate_sampled.gifconvert rose: -scale 25% -scale 70×46\! rose_pixelate_scaled.gifconvert rose: -resize 25% -scale 70×46\! rose_pixelate_resized.gif
Grids of Pixels
Gridding an image is very similar to pixelating an image. In this case we want only want to enlarge the image, to generate distinct pixel-level view of a image’s details. Typically a very small image. The simplest way is like the previous example, simply Scale a small image, to enlarge the pixels.
convert rose: -crop 10×10+12+20 +resize grid_input.pngconvert grid_input.png -scale 1000% grid_scale.pngThe problem with a simple scaling, is that in areas where pixels are similar in color, you can have trouble seeing the individual ‘pixel blocks’. What we need to add a border around the pixels, to separate them. For this we need to overlay a generated tile mask. See Tiling with an Image already In Memory for various methods of using a generated tiling image, in a single command.
Here we generate a white on black ‘grid’ which is overlayed using Screen Composition (overlay white, while leaving black areas as-is).
convert -size 10x10 xc: -draw 'rectangle 1,1 9,9' -write mpr:block +delete \
grid_input.png -scale 1000% -size 101x101 tile:mpr:block \
+swap -compose screen -composite grid_blocks.png
Note that the size used to generate the tile is scale*image_size+gap_size (in this case 10*10+1 => 101). I also Swapped the two images so that the final image size comes from the tile image, rather than from the scaled image which is one pixel smaller in size. However this may lose any image meta-data that was in the original image as I used the tiled image for the destination.
Here I generate circular ‘spots’ of color, but this time used a Multiply Composition (overlay black, while leaving white areas as-is).
convert -size 10x10 xc: -draw 'circle 5,5 1,3' -negate -write mpr:spot +delete \ grid_input.png -scale 1000% -size 101x101 tile:mpr:spot \ +swap -compose multiply -composite grid_spots.png
You can make the grid border transparent by also negating the tiled overlay (black areas become transparent) and use a CopyOpacity Composition instead of Multiply. Other colors can also be added, but for this to work you have to use a tile image that actually contains real transparency. For this you need to convert the black and white tile image into a Shaped Mask.
For example, here I use Basic Morphology Operator to generate a diamond shaped ‘holes’ in a colored overlay. For this a single ‘seed’ pixel is drawn and expanded using a Diamond Morphology Kernel.
convert -size 10x10 xc: -draw 'point 5,5' -morphology Erode:4 Diamond \ -background Navy -alpha shape -write mpr:diamond +delete \ grid_input.png -scale 1000% -splice 1x1+0+0 \ -size 101x101 -background none tile:mpr:diamond \ -alpha set -compose Over -composite grid_diamonds.png
Note that the "tile:" coder will replace any transparency in the image with the current background color. If you want to preserve the transparency of the tiling image, either set "-background none" or "-compose Src". The former is easier.
Note techniqually, the alpha shaping can be done either before saving the tile image, or after tiling the tile image, before overlaying it. The choice is yours. One final technique is to use a bad resampling filter to produce a Resampling Failure to generate aliased circles of each pixel. This is not great technique (mis-using image processing failure), but it does form a Grid of Pixels.
—
# longueur de l'image
w=`convert $infile -format "%[fx:w]" info:`
# largeur de l'image
h=`convert $infile -format "%[fx:h]" info:`
minify=`convert xc: -format "%[fx:100/$size]" info:`
# process image convert $infile -resize $minify% -scale ${w}x${h}! $outfile
Try replacing -resize with -scale or possibly better with -sample.
—-
PS. I believe that the max operation is already available in -morphology dilate on a colored image
convert tractor_sm.png -morphology dilate square:4 tractor_sm_dilate4.png
—Optimal Settings For ImageMagick
ImageMagick Basics
ImageMagick has a ton of options and functions, and finding a good combination of these can be tricky. Two main ImageMagick settings are of interest to us, convert and mogrify. Both of these perform similar operations, but mogrify is intended to be used with multiple files at once, while convert handles only one image at a time. A simple ImageMagick operation might look like this:
convert input.jpg -resize 300 output.jpg
This says that we want ImageMagick’s convert function to take input.jpg and resize it to 300 pixels wide, and then save that to output.jpg. The -resize 300 part is an example of one of ImageMagick’s many built-in functions. Each function uses the same format: -functionName option. Using mogrify is similar, but with the syntax reordered a bit:
mogrify -path output/ -resize 300 *.jpg
This says that we want ImageMagick’s mogrify function to take all JPEG files in the current directory (*.jpg), resize them to 300 pixels wide and then save them in the output directory. Functions can be combined for more complex results:
convert input.jpg -resize 300 -quality 75 output.jpg
As before, this resizes input.jpg to 300 pixels wide, but this time it also sets the JPEG quality to 75 before saving it to output.jpg. I’ve performed <>hundreds of tests<> to see which combinations of functions and options produce the smallest results at an acceptable quality.
Testing and Results
The lower the score, the more the images resemble each other; a score of zero means they are identical.
a score of 0.015 were indistinguishable to their test users.
mogrify -path OUTPUT_PATH -filter Triangle -define filter:support=2 \ -thumbnail OUTPUT_WIDTH -unsharp 0.25x0.25+8+0.065 -dither None \ -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off \ -define png:compression-filter=5 -define png:compression-level=9 \ -define png:compression-strategy=1 -define png:exclude-chunk=all \ -interlace none -colorspace sRGB -strip INPUT_PATH
Mogrify vs. Convert
As mentioned, ImageMagick provides two similar tools for manipulating images: convert is the basic image editor and works on one image at a time; mogrify is mostly used for batch image manipulation. In an ideal world, these two tools would produce identical results; unfortunately, that’s not the case — convert has a bug that makes it ignore one of the settings I recommend using (the -define jpeg:fancy-upsampling=off setting, discussed below), so using mogrify is better.
Resampling
The most obvious resizing function to use is -resize, but it creates files that are too large. I looked at 11 different functions and found that -thumbnail does the best job of optimizing quality and file size. In most cases, the -thumbnail function uses a three-step process to resize images:
This means that if we were resizing an image to be 500 pixels wide, -thumbnail would first resize it to 2,500 pixels wide using -sample; the result might be blocky and pixelated, as we saw in the examples above, but the operation would be fast and would produce a result with a small file size. Then, ImageMagick would resize this image from 2,500 pixels wide to 500 pixels wide using -resize. This smooths out the blockiness, but the file size stays pretty low. Finally, ImageMagick would remove meta data to get an even smaller file. The second way to choose a resampling filter in ImageMagick is with the -filter setting. Some resizing functions (such as -sample) have a built-in resampling function that’s always used, but others (such as -resize) have defaults that can be overridden with -filter. The -filter setting gets used in -thumbnail’s second step, because that step uses -resize. I tested 31 different settings for -filter and got the best results with Triangle. The Triangle resampling filter is also known as bilinear interpolation, which I discussed above. It determines pixel color by looking at a support area of neighboring pixels and produces a weighted average of their colors. I found it best to specify this support area at two pixels using the -define filter:support=2 setting. The third way to choose a resampling filter, the -interpolate setting, is ignored by -thumbnail, so it’s not needed here. In addition to the settings above, by default ImageMagick also uses something called JPEG fancy upsampling, an algorithm that tries to produce better-looking JPEGs. I’ve found that it produces larger files and that the quality difference is negligible, so I recommend turning it off with -define jpeg:fancy-upsampling=off.
Sharpening
Images pretty often get a little blurry when resized, so programs such as Photoshop will often apply some sharpening afterwards to make the images a little crisper. I recommend using an unsharp filter — which, despite its name, actually does sharpen the image — with the setting -unsharp 0.25×0.25+8+0.065. Unsharp filters work by first applying a Gaussian blur to the image. The first two values for the unsharp filter are the radius and sigma, respectively — in this case, both have a value of 0.25 pixels. These values are often the same and, combined, tell ImageMagick how much to blur the image. After the blur is applied, the filter compares the blurred version to the original, and in any areas where their brightness differs by more than a given threshold (the last value, 0.065), a certain amount of sharpening is applied (the third value, 8). The exact meanings of the threshold and numerical amounts aren’t very important; just remember that a higher threshold value means that sharpening will be applied less often, and a higher numerical amount means that the sharpening will be more intense wherever it is applied.
Color Reduction
One way to reduce colors is with posterization, a process in which gradients are reduced to bands of solid color. Posterization reduces colors to a certain number of color levels — that is, the number of colors available in each of the red, green and blue color channels that images use. The total number of colors in the final image will be a combination of the colors in these three channels. Posterization can drastically reduce file size, but can also drastically change how an image looks.
With many color levels — for example, 136, as I’m suggesting — you get a smaller file without losing much image quality.
Posterization reduces the colors in the image. (Image: Richard Fisher) (View large version)
Dithering is a process that is intended to mitigate color banding by adding noise into the color bands to create the illusion that the image has more colors. In theory, dithering seems like a good idea when you posterize; it helps the viewer perceive the result as looking more like the original.Dithering. Unfortunately, ImageMagick has a bug that ruins images with transparency when dithering is used like this. So, it’s best to turn dithering off with -dither None. Luckily, even without dithering, the posterized images still look good.
ImageMagick dithering bug.
Color Space Link
While not strictly a matter of color reduction, setting an image’s color space is a related concept. The color space defines what colors are available for an image. The image below shows that the ProPhoto RGB color space contains more colors than the Adobe RGB color space, which in turn contains more colors than the sRGB color space. All of these contain fewer colors than are visible to the human eye.
sRGB was created to be the one true king of color spaces on the Internet. It has been endorsed by the W3C and other standards bodies; it is the required color space in the CSS Color Module Level 3 and the SVG specification and is the assumed color space of the WebP specification; and it is explicitly referenced in the PNG specification. It’s also the default color space in Photoshop. In short, sRGB is the color space of choice for the web platform, and, assuming you want your images to render predictably, using it is probably a good idea.
Quality and Compression
With lossy image formats such as JPEG, quality and compression go hand in hand: the higher the compression, the lower the quality and the lower the file size. We could drastically reduce file size by setting a high JPEG compression factor, but this would also drastically reduce quality. A balance is needed. When I was doing my tests, the control images I created with Photoshop had a JPEG quality setting of high, or 60. I’ve found that this setting works well for me and strikes the right balance between quality and file size. However, in my ImageMagick settings, I’m recommending -quality 82. Why? It turns out that JPEG quality scales are not defined in a specification or standard, and they are not uniform across encoders. A quality of 60 in Photoshop might be the same as a quality of 40 in one program, quality B+ in another and quality fantastico in a third. In my tests, I found that Photoshop’s 60 is closest to -quality 82 in ImageMagick. For non-lossy image formats, such as PNG, quality and compression are not related at all. High compression doesn’t change how an image looks at all and only comes at the expense of processing load (in terms of CPU usage, memory usage and processing time). Assuming that our computers can handle this load, there’s no reason not to max out PNG compression.
PNG compression in ImageMagick can be configured with three settings, -define png:compression-filter, -define png:compression-level and -define png:compression-strategy.
I got the best results using adaptive filtering (-define png:compression-filter=5). Compression level is the amount of compression that gets applied; I recommend maxing this out to 9 (-define png:compression-level=9). Finally, the compression strategy setting determines the actual algorithm that’s used to compress the files; I got the best result with the default compression strategy (-define png:compression-strategy=1).
Meta Data
-thumbnail doesn’t remove all of the meta data, and there are gains to be had by using -strip and -define png:exclude-chunk=all as well. Neither of these should affect quality at all.
Progressive Rendering
JPEGs and PNGs can be saved to use either progressive or sequential rendering. Sequential rendering is usually the default: The image will load pixels row by row from top to bottom. Progressive rendering means the image is delivered and rendered in stages. For JPEGs, progressive rendering can happen in any number of stages, as determined when the file is saved. The first stage will be a very low-resolution version of the full image; at each subsequent stage, a higher-resolution version is delivered until, in the last stage, the full-quality version is rendered.
Progressive JPEG simulation. PNGs use a type of progressive rendering called Adam7 interlacing, in which the pixels of the image are delivered in seven stages based on an 8 × 8 pixel grid.
Adam7 interlacing. Both types of progressive rendering can be controlled in ImageMagick using the -interlace setting. But should progressive rendering be turned on or not? For both JPEGs and PNGs, progressive rendering increases the file size, but for a long time conventional wisdom held that it was worth turning on because it delivered a better experience to the user. The idea is that even if the full, perfect image doesn’t load quite as quickly, users would be able to see something earlier, and that something is probably better than nothing. Last year, though, Radware released research on progressive JPEGs that shows users actually tend to prefer sequential image rendering. This is just one study (and one that hasn’t gone through a formal peer review process), but the results are interesting. Radware’s results, combined with the fact that sequential images have smaller file sizes, lead me to recommend the -interlace none setting in ImageMagick.
Image Optimization
I mentioned above that I ran tests both with and without image optimization. All of the settings I’ve described so far are what I’d recommend if you’re not optimizing your images. If you can optimize them, though, my recommendations would change slightly: I found that slightly different -unsharp settings work better (-unsharp 0.25×0.08+8.3+0.045 versus -unsharp 0.25×0.25+8+0.065 without optimization) and that there’s no need to use -strip.
mogrify -path OUTPUT_PATH -filter Triangle -define filter:support=2 \ -thumbnail OUTPUT_WIDTH -unsharp 0.25x0.08+8.3+0.045 -dither None \ -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off \ -define png:compression-filter=5 -define png:compression-level=9 \ -define png:compression-strategy=1 -define png:exclude-chunk=all \ -interlace none -colorspace sRGB INPUT_PATH
A lot of different image optimizers are out there. I tested image_optim, picopt and ImageOptim, all of which run images through a battery of different optimization steps. I tested these tools both individually and in combination, and I found that the best results come from running files through all three, in the order listed above. That said, there are diminishing returns: After the first round of optimization with image_optim, the extra compression that picopt and ImageOptim achieve is quite small. Unless you have a lot of time and processing power, using multiple image optimizers is probably overkill.
How To Implement This In Your Projects
I hope the benefits of using this technique are obvious. Luckily for you, the hard part — figuring all of this out — is all done. Despite the apparent complexity of the recommended settings, implementing this in your own projects can be fairly quick and easy. Although running this whopper of a command from the terminal every time you want to resize an image may be inconvenient, there are simpler options that require very little muss or fuss.
bash shell
you can add a function to your .bash_aliases (or .bashrc) file that acts as an alias for my recommended command:
smartresize() { mogrify -path $3 -filter Triangle -define filter:support=2 \ -thumbnail $2 -unsharp 0.25x0.08+8.3+0.045 -dither None \ -posterize 136 -quality 82 -define jpeg:fancy-upsampling=off \ -define png:compression-filter=5 -define png:compression-level=9 \ -define png:compression-strategy=1 -define png:exclude-chunk=all \ -interlace none -colorspace sRGB $1 }
Then, you can call it like this:
smartresize inputfile.png 300 outputdir/
PHP Link
PHP has ImageMagick integration called Imagick that makes it relatively easy to run ImageMagick operations from within your PHP scripts. Unfortunately, Imagick is a bit limited and doesn’t let you do some things that I recommend, like setting a resampling filter to be used with the thumbnail function. But, again, you’re in luck: I’ve created a composer package called php-respimg (packagist) that handles everything described above. You can include it in your projects with Composer by running:
composer require nwtn/php-respimg
Then, you can resize your images like this:
require_once('vendor/autoload.php'); use nwtn\Respimg as Respimg; $image = new Respimg($input_filename); $image->smartResize($output_width, 0, false); $image->writeImage($output_filename);
Content Management Systems
If you use a CMS, you might want to take advantage of these savings for the thumbnails and other resized images that get generated when users upload images. A few options are available to you. If your CMS is built on PHP, you could bake the PHP stuff above into a theme or plugin. However, if your PHP-based CMS happens to be WordPress, then there’s no need for you to do that work: This is now integrated into the Responsive Issues Community Group’s plugin RICG Responsive Images as an experimental feature. After you install the plugin, all you’ll need to do to activate these ImageMagick settings is add the following lines to your functions.php file:
function custom_theme_setup() { add_theme_support( 'advanced-image-compression' ); } add_action( 'after_setup_theme', 'custom_theme_setup' );
If you don’t use WordPress and don’t want to try to hack this into your CMS, most CMS’ include some way to modify image defaults (especially for quality). You might be able to get a lot of these benefits with a few simple changes to your CMS’ configuration. Check out the documentation and see what options are available to you.
Commentaires
I also use IM to resize and sharpen images, but mostly for the better quality output compared to Photoshop
Here is my script:
for file in *.jpg ; do convert $file -resize 1012x -unsharp 0x0.55+0.55+0.008 -quality 90% small-$file ; done