ImageMagick convert

ImageMagick简介

  ImageMagick是一个适用于创建、编辑和组合位图的软件。它能够读、写和转换超过百余种格式的图片。

  另外,ImageMagick针对主流的编程语言都有借口,包括G2F (Ada), MagickCore (C), MagickWand (C), ChMagick (Ch), ImageMagickObject (COM+), Magick++ (C++), JMagick (Java), L-Magick (Lisp), NMagick (Neko/haXe), MagickNet (.NET), PascalMagick (Pascal), PerlMagick (Perl), MagickWand for PHP (PHP), IMagick (PHP), PythonMagick (Python), RMagick (Ruby), 和 TclMagick (Tcl/TK)。当然,你也可以通过命令行的方式将它与其它程序组合起来。

  ImageMagick是一个开源软件,以可运行的二进制文件和源代码两种方式发布。你可以在公开和私有的程序中随意地使用、复制、修改和分发它。它基于Apache 2.0风格的协议发布。



ImageMagick使用实例

Image MagicK 是一个强大的图象处理工具包。它提供了几个非常方 便的命令行命令: display, animate,import, montage,mogrify,identify等,可以进行图象的显示,缩放,旋转, 调色,加框,加注释等,还能制作GIF动画,图象索引,能自动生成 图象.

  1. 制作索引图和动画
    !/bin/bash
    montage -bordercolor red -borderwidth 3 -label "%f" -tile 5x3 *.JPG montage.jpg
    mogrify -format gif *.JPG
    display montage.jpg
    animate *.JPG
    
  2. 缩放 convert -sample 80x40 input.jpg output.jpg #注意:缩放后图像保持原来的长宽比例 convert -sample 25%x25% input.jpg output.jpg
  3. 为当前目录的所有图像生成缩略图
    for img in `ls *.jpg`
     do
       convert -sample 25%x25% $img thumb-$img
     done
    
  4. 获取文件信息 libtiff
    tiffinfo filename.tiff
    pnginfo filename.png
    
  5. 可以使用 ImageMagick 的 identify
     identify -verbose sample.png 
     identify -format "%wx%h" sample.png 
    
  6. 旋转图像
     convert -rotate 90 input.jpg output.jpg
    
  7. 更改文件类型
     convert input.jpg output.png
    
  8. 为图像增加注释文字
    convert -font helvetica -fill white -pointsize 36 \
     -draw 'text 10,50 "Floriade 2002, Canberra, Australia"' \
     floriade.jpg comment.jpg 
    convert -font fonts/1900805.ttf -fill white -pointsize 36 \
     -draw 'text 10,475 "stillhq.com"' \
     floriade.jpg stillhq.jpg 
    
  9. 特殊效果
    convert -charcoal 2 input.jpg output.jpg #炭笔
    convert -colorize 255 input.jpg output.jpg #着色 可以指定三种颜色 red/green/blue
    convert -implode 4 input.jpg output.jpg  #内爆效果
    convert -solarize 42 input.jpg output.jpg #曝光,模拟胶片曝光
    convert -spread 5 input.jpg output.jpg  #随机移动,参数是位移大小
    
  10. 一次执行多个操作
     convert -sample 25%x25% -spread 4  -charcoal 4 input.jpg output.jpg 
    

ImageMagick FAQ 摘要

  1. 如何让animate在显示图片的过程保持窗口的标题不变
    animate -title "My Image Sequence" images.
    
  2. import抓得的图片与X服务器上显示的不一致怎么办?
    import -descend image.miff
    
  3. 如何动画显示YUV 图片序列?
    animate -geometry 352x240 -scene 0-71 yuv3:frame%d
    
  4. 如果只看一个RGB图片的红色通道(red channel)?
    display -gamma 1.0,0.0,0.0 image.miff
    
  5. 如何改变PostScript默认纸张大小?
    要改变默认的612x792大小,修改magick/image.h中的PSPageGeometry的值并重编译.
  6. 如何自左至右无边无框无文字半三幅画连接在一起?
    convert +append image1.ppm image2.ppm image3.ppm side_by_side.miff
     # 或
    convert -size 350x500 xc:black composite.miff
    composite -geometry +0+0 composite.miff image1.gif composite.miff
    composite -geometry +100+0 composite.miff image2.gif composite.miff
    composite -geometry +0+300 composite.miff image3.gif composite.miff
    composite -geometry +0+375 composite.miff image4.gif composite.miff
    
  7. 如何生成gif动画?
    convert -delay 20 frame*.gif animation.gif
    convert -delay 20 frame1.gif -delay 10 frame2.gif -delay 5 frame3.gif animation.gif
    convert frame1.gif -page +50+100 frame2.gif -page +0+100 frame3.gif animation.gif
    convert -loop 50 frame*.gif animation.gif
    convert +adjoin images.* frames%d.gif
    
  8. 如果完整的显示PostScript图片?
    display -page letter image.ps
    
  9. 什么是图片目录?如何使用它们?
    #图片目录(visual image directory ,VID)的创建:
       montage *.jpg directory.vid
       convert 'vid:*.jpg' directory.vid
    #显示图片目录
       display directory.vid
       display vid:movie.mpg
    
  10. 如果带框架保存一个窗口?
    xwininfo -frame
    import -frame -window ID window.miff
    
  11. 图片以单一颜色(a solid color)显示,是怎么回事? 图片被破坏,或含有值为0的matte层,试着:
     display +matte image.miff
    
  12. 出现 "???? library is not available ..."是怎么回事? 没安装相关的函数库。参见安装说明。
  13. 如何查看图片不光滑层(matte channel)的值?
    convert image.tiff image.matte
    display -size 640x480 gray:image.matte
    
  14. 运行"Convert in.gif out.png" 时显示 "Invalid Parameter - out. 你运行的convert是windows的分区类型转换程序。
  15. 如何在图片增加斜角?
    #对图片边缘的处理共分四类。
     1)增加有色边
    convert -bordercolor red -border 25x25 image.jpg image.gif
     2)加亮或变暗图片边缘,以增强3D效果
    convert -raise 25 image.jpg image.gif
     3)在图片周围增加装饰性框架。
    convert -mattecolor gray -frame 25x25 image.jpg image.gif
     4)在图片边缘增加升、降斜角
    convert -mattecolor gray -frame 25x25+0+25 image.jpg image.gif
    convert -mattecolor gray -frame 25x25+25+0 image.jpg image.gif
    
  16. 用窗口管理器运行display失败了,怎么办? 用下列命令之一来确认display运行在一个交互环境中:
    display logo:Untitled
    display < /dev/console
    
  17. 将PostScript文件转换为其它格式时,如何改善文字的外观?
    convert -density 288 -geometry 25% image.ps image.gif
    
  18. 如何用2-3英寸高的文字注释一个图片? 先检查有无可缩放字体: xlsfonts -fn '*-0-0-0-0-*' 有则:
    convert -font '-*-helvetica-*-*-*--300-300-*-*-*-*-iso8859-1' \
            -fill green -draw 'text 50,300 Magick' image.gif annotated.gif
    # If you have the FreeType support built into ImageMagick,
    # just increase your pointsize and/or density:
    convert -font Helvetica -pointsize 100 -density 300 ...
    
  19. 如何将gif文件分析为一系列的单个图片?
    convert animation.gif frame%02d.gif
    
  20. 用NetScape显示的图片,如何去掉周围的背景色? convert +page alpha.gif beta.gif
  21. 如何用web安全的颜色(Web safe colors)创建GIF或PNG图片?
    convert -map netscape: alpha.gif beta.gif
    
  22. 为何Adobe Acrobat 2.1不能读ImageMagick's制作的PDF? 用 Acrobat 3.0或以上版本,来阅读这种经zip压缩的pdf,或制作PDF时不进行压缩。
    convert +compress images.tiff image.pdf
    
  23. 如何在图片上增加一个不光滑层(matte channel)?
    convert image.gif -matte temp.miff
    composite -compose CopyOpacity mask.xbm temp.miff transparent.gif
    
  24. 在NT环境下如何用convert在图片上写字?
    convert -font Arial -fill blue -draw "text 10,10 'your text here'" d:\test.tif png:d:\test.png
    convert.exe -pointsize 18 -draw "text 0,0 "This is my text!"" C:\blank.gif c:\text.gif
    
  25. 为何GIF文件比期望的大? 需要在编译源码时加 --enable-lzw 参数,来打开LZW压缩功能。
  26. 为何JPEG文件比期望的大? 可能嵌入Exif或IPTC等"profiles", 或者含有没压缩的thumbnails. 可以用命令行参数 +profile ""或相关的API来将它们去掉。
  27. 如何从图片文件中抽取第一张图片?
    convert "Image.gif[0]" first.gif
    
  28. 如何创建一张空白图片?
    convert -size 800x600 xc:"#ddddff" ltblue.ppm
    convert -size 800x600 null:white white.ppm
    convert in.png -threshold 100% black.ppm #<--与in.png同大小
    
     
  29. 为何GIF文件比期望的大? 需要在编译源码时加 --enable-lzw 参数,来打开LZW压缩功能。
  30. 为何JPEG文件比期望的大? 可能嵌入Exif或IPTC等"profiles", 或者含有没压缩的thumbnails. 可以用命令行参数 +profile ""或相关的API来将它们去掉。

使用笔记

  1. 把matlab中画出的多幅图作成GIF动画
     for i in `ls *.jpg`; do convert -trim -resize 350x305 $i crop.$i; done
     convert -delay 10 -loop 3 crop.frame*.jpg string.gif
     rm crop.frame*.jpg
    
  2. 生成png格式的email地址
    convert -size 185x19 null:white email.png
    convert -font monospace -fill black -pointsize 16  -draw 'text 4,14 "youremail@yourdomain"' email.png email.png 
    convert -font monospace -fill blue -pointsize 16  -draw 'text 3,13 "youremail@yourdomain"' email.png email.png 
    

~~~~~~~~~~~~~~~~~~~~
convert -crop 300x300+0+0 -resize 200x200 -colors 100 +profile "*" 1.jpg 1.png

表示:把1.jpg先从左上角(0,0)为起点裁剪一块300x300的部分,然后把这部分缩小到200x200,然后把颜色缩减到100色,最后生成1.png。
+profile "*": 意味着在图片文件里不存储附加信息,以减小图片体积。
注意,-resize会试图保留原图的视觉比例,因此不一定生成的图片和你指定的尺寸一定匹配,比如,如果2.jpg大小是400x200,所以如果用命令:convert 2.jpg -resize 100x100 2.png,那么生成的图片2.png的实际大小是100x50。

常用的参数有:

 

-crop 宽x高+起点横坐标+起点纵坐标:裁剪图
-resize 宽x高!:改变尺寸,如果使用惊叹号,表示不保留视觉比例,强行改变尺寸匹配给定的宽和高;如果仅给定宽或者高,如“宽x”或“x高”形式的参数(“x高”与“宽x高”的效果是一样的),则以已知参数为基准按比例改变尺寸。
-colors 颜色数:设定图片采用的颜色数,如果是生成png或gif图片应指定这个参数
-quality 质量:设定jpeg图片输出质量,推荐采用80,此命令仅用于输出格式是jpg的情况,不应省略,省略的话默认质量是95,生成图片过大
+profile "*":图片中不存储附加信息,必须使用,否则生成图片过大



convert.exe工具命令列表

Use the convert program to convert between image formats as well as resize an image, blur, crop, despeckle, dither, draw on, flip, join, re-sample, and much more. See Command Line Processing for advice on how to structure your convert command or see below for example usages of the command.

Example Usage

We list a few examples of the convert command here to illustrate its usefulness and ease of use. To get started, lets convert an image in the JPEG format to PNG:

convert rose.jpg rose.png

Next, we reduce the image size before it is written to the PNG format:

convert rose.jpg -resize 50% rose.png

rose ==> rose

You can combine multiple image-processing operations to produce complex results:

convert -size 320x85 canvas:none -font Bookman-DemiItalic -pointsize 72 \ 
-draw "text 25,60 'Magick'" -channel RGBA -blur 0x6 -fill darkred -stroke magenta \ 
-draw "text 20,55 'Magick'" fuzzy-magick.png

fuzzy-magick

or here we resize an image with improved quality:

convert input.png -colorspace RGB +sigmoidal-contrast 11.6933 \ 
-define filter:filter=Sinc -define filter:window=Jinc -define filter:lobes=3 \ 
-resize 400% -sigmoidal-contrast 11.6933 -colorspace sRGB output.png

You can find additional examples of using convert in Examples of ImageMagick Usage.

Option Summary

The convert command recognizes these options. Click on an option to get more details about how that option works.

OptionDescription
-adaptive-blur geometryadaptively blur pixels; decrease effect near edges
-adaptive-resize geometryadaptively resize image with data dependent triangulation.
-adaptive-sharpen geometryadaptively sharpen pixels; increase effect near edges
-adjoinjoin images into a single multi-image file
-affine matrixaffine transform matrix
-alphaon, activate, off, deactivate, set, opaque, copy", transparent, extract, background, or shape the alpha channel
-annotate geometry textannotate the image with text
-antialiasremove pixel-aliasing
-appendappend an image sequence
-authenticate valuedecipher image with this password
-auto-gammaautomagically adjust gamma level of image
-auto-levelautomagically adjust color levels of image
-auto-orientautomagically orient image
-background colorbackground color
-bench iterationsmeasure performance
-bias valueadd bias when convolving an image
-black-threshold valueforce all pixels below the threshold into black
-blue-primary pointchromaticity blue primary point
-blue-shift factorsimulate a scene at nighttime in the moonlight
-blur geometryreduce image noise and reduce detail levels
-border geometrysurround image with a border of color
-bordercolor colorborder color
-brightness-contrastgeometryimprove brightness / contrast of the image
-canny geometryuse a multi-stage algorithm to detect a wide range of edges in the image
-caption stringassign a caption to an image
-cdl filenamecolor correct with a color decision list
-channel typeapply option to select image channels
-charcoal radiussimulate a charcoal drawing
-chop geometryremove pixels from the image interior
-clampset each pixel whose value is below zero to zero and any the pixel whose value is above the quantum range to the quantum range (e.g. 65535) otherwise the pixel value remains unchanged.
-clipclip along the first path from the 8BIM profile
-clip-mask filenameassociate clip mask with the image
-clip-path idclip along a named path from the 8BIM profile
-clone indexclone an image
-clutapply a color lookup table to the image
-contrast-stretch geometryimprove the contrast in an image by `stretching' the range of intensity value
-coalescemerge a sequence of images
-colorize valuecolorize the image with the fill color
-color-matrix matrixapply color correction to the image.
-colors valuepreferred number of colors in the image
-colorspace typeset image colorspace
-combinecombine a sequence of images
-comment stringannotate image with comment
-comparecompare image
-complexoperatorperform complex mathematics on an image sequence
-compose operatorset image composite operator
-compositecomposite image
-compress typeimage compression type
-contrastenhance or reduce the image contrast
-convolve coefficientsapply a convolution kernel to the image
-crop geometrycrop the image
-cycle amountcycle the image colormap
-decipher filenameconvert cipher pixels to plain
-debug eventsdisplay copious debugging information
-define format:optiondefine one or more image format options
-deconstructbreak down an image sequence into constituent parts
-delay valuedisplay the next image after pausing
-delete indexdelete the image from the image sequence
-density geometryhorizontal and vertical density of the image
-depth valueimage depth
-despecklereduce the speckles within an image
-direction typerender text right-to-left or left-to-right
-display serverget image or font from this X server
-dispose methodlayer disposal method
-distribute-cache portlaunch a distributed pixel cache server
-distort type coefficientsdistort image
-dither methodapply error diffusion to image
-draw stringannotate the image with a graphic primitive
-duplicate count,indexesduplicate an image one or more times
-edge radiusapply a filter to detect edges in the image
-emboss radiusemboss an image
-encipher filenameconvert plain pixels to cipher pixels
-encoding typetext encoding type
-endian typeendianness (MSB or LSB) of the image
-enhanceapply a digital filter to enhance a noisy image
-equalizeperform histogram equalization to an image
-evaluate operator valueevaluate an arithmetic, relational, or logical expression
-evaluate-sequence operatorevaluate an arithmetic, relational, or logical expression for an image sequence
-extent geometryset the image size
-extract geometryextract area from image
-family namerender text with this font family
-features distanceanalyze image features (e.g. contract, correlations, etc.).
-fftimplments the discrete Fourier transform (DFT)
-fill colorcolor to use when filling a graphic primitive
-filter typeuse this filter when resizing an image
-flattenflatten a sequence of images
-flipflip image in the vertical direction
-floodfill geometry colorfloodfill the image with color
-flopflop image in the horizontal direction
-font namerender text with this font
-format stringoutput formatted image characteristics
-frame geometrysurround image with an ornamental border
-function nameapply a function to the image
-fuzz distancecolors within this distance are considered equal
-fx expressionapply mathematical expression to an image channel(s)
-gamma valuelevel of gamma correction
-gaussian-blur geometryreduce image noise and reduce detail levels
-geometry geometrypreferred size or location of the image
-gravity typehorizontal and vertical text placement
-grayscale methodconvert image to grayscale
-green-primary pointchromaticity green primary point
-helpprint program options
-hough-lines geometryidentify lines in the image
-identifyidentify the format and characteristics of the image
-iftimplements the inverse discrete Fourier transform (DFT)
-implode amountimplode image pixels about the center
-insert indexinsert last image into the image sequence
-intensity methodmethod to generate an intensity value from a pixel
-intent typetype of rendering intent when managing the image color
-interlace typetype of image interlacing scheme
-interline-spacing valuethe space between two text lines
-interpolate methodpixel color interpolation method
-interword-spacing valuethe space between two words
-kerning valuethe space between two characters
-label stringassign a label to an image
-lat geometrylocal adaptive thresholding
-layers methodoptimize or compare image layers
-level valueadjust the level of image contrast
-limit type valuepixel cache resource limit
-linear-stretch geometrylinear with saturation histogram stretch
-liquid-rescale geometryrescale image with seam-carving
-list typeColor, Configure, Delegate, Format, Magic, Module, Resource, or Type
-log formatformat of debugging information
-loop iterationsadd Netscape loop extension to your GIF animation
-mask filenameassociate a mask with the image
-mattecolor colorframe color
-median radiusapply a median filter to the image
-mean-shift geometrydelineate arbitrarily shaped clusters in the image
-metric typemeasure differences between images with this metric
-mode radiusmake each pixel the 'predominant color' of the neighborhood
-modulate valuevary the brightness, saturation, and hue
-momentsdisplay image moments.
-monitormonitor progress
-monochrometransform image to black and white
-morph valuemorph an image sequence
-morphology method kernelapply a morphology method to the image
-motion-blur geometrysimulate motion blur
-negatereplace each pixel with its complementary color
-noise radiusadd or reduce noise in an image
-normalizetransform image to span the full range of colors
-opaque colorchange this color to the fill color
-ordered-dither NxNordered dither the image
-orient typeimage orientation
-page geometrysize and location of an image canvas (setting)
-paint radiussimulate an oil painting
-perceptibleset each pixel whose value is less than |epsilon| to -epsilon or epsilon (whichever is closer) otherwise the pixel value remains unchanged.
-pingefficiently determine image attributes
-pointsize valuefont point size
-polaroid anglesimulate a Polaroid picture
-poly termsbuild a polynomial from the image sequence and the corresponding terms (coefficients and degree pairs).
-posterize levelsreduce the image to a limited number of color levels
-precision valueset the maximum number of significant digits to be printed
-preview typeimage preview type
-print stringinterpret string and print to console
-process image-filterprocess the image with a custom image filter
-profile filenameadd, delete, or apply an image profile
-quality valueJPEG/MIFF/PNG compression level
-quantize colorspacereduce image colors in this colorspace
-quietsuppress all warning messages
-radial-blur angleradial blur the image
-raise valuelighten/darken image edges to create a 3-D effect
-random-threshold low,highrandom threshold the image
-red-primary pointchromaticity red primary point
-regard-warningspay attention to warning messages.
-region geometryapply options to a portion of the image
-remap filenametransform image colors to match this set of colors
-renderrender vector graphics
-repage geometrysize and location of an image canvas
-resample geometrychange the resolution of an image
-resize geometryresize the image
-respect-parenthesessettings remain in effect until parenthesis boundary.
-roll geometryroll an image vertically or horizontally
-rotate degreesapply Paeth rotation to the image
-sample geometryscale image with pixel sampling
-sampling-factor geometryhorizontal and vertical sampling factor
-scale geometryscale the image
-scene valueimage scene number
-seed valueseed a new sequence of pseudo-random numbers
-segment valuessegment an image
-selective-blur geometryselectively blur pixels within a contrast threshold
-separateseparate an image channel into a grayscale image
-sepia-tone thresholdsimulate a sepia-toned photo
-set attribute valueset an image attribute
-shade degreesshade the image using a distant light source
-shadow geometrysimulate an image shadow
-sharpen geometrysharpen the image
-shave geometryshave pixels from the image edges
-shear geometryslide one edge of the image along the X or Y axis
-sigmoidal-contrastgeometryincrease the contrast without saturating highlights or shadows
-smush offsetsmush an image sequence together
-size geometrywidth and height of image
-sketch geometrysimulate a pencil sketch
-solarize thresholdnegate all pixels above the threshold level
-splice geometrysplice the background color into the image
-spread radiusdisplace image pixels by a random amount
-statistic type geometryreplace each pixel with corresponding statistic from the neighborhood
-stripstrip image of all profiles and comments
-stroke colorgraphic primitive stroke color
-strokewidth valuegraphic primitive stroke width
-stretch typerender text with this font stretch
-style typerender text with this font style
-swap indexesswap two images in the image sequence
-swirl degreesswirl image pixels about the center
-synchronizesynchronize image to storage device
-taintmark the image as modified
-texture filenamename of texture to tile onto the image background
-threshold valuethreshold the image
-thumbnail geometrycreate a thumbnail of the image
-tile filenametile image when filling a graphic primitive
-tile-offset geometryset the image tile offset
-tint valuetint the image with the fill color
-transformaffine transform image
-transparent colormake this color transparent within the image
-transparent-color colortransparent color
-transposeflip image in the vertical direction and rotate 90 degrees
-transverseflop image in the horizontal direction and rotate 270 degrees
-treedepth valuecolor tree depth
-trimtrim image edges
-type typeimage type
-undercolor colorannotation bounding box color
-unique-colorsdiscard all but one of any pixel color.
-units typethe units of image resolution
-unsharp geometrysharpen the image
-verboseprint detailed information about the image
-versionprint version information
-viewFlashPix viewing transforms
-vignette geometrysoften the edges of the image in vignette style
-virtual-pixel methodaccess method for pixels outside the boundaries of the image
-wave geometryalter an image along a sine wave
-weight typerender text with this font weight
-white-point pointchromaticity white point
-white-threshold valueforce all pixels above the threshold into white
-write filenamewrite images to this file
  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值