天天看點

linux的convert圖檔處理工具

得到一個圖檔的尺寸,

identify test.png

結果為:

test.png PNG 178x15 178x15+0+0 16-bit PseudoClass 65536c 2.28kb

使用shell

identify test.png | cut -d ' ' -f 3 | cut -d 'x' -f 1

identify test.png | cut -d ' ' -f 3 | cut -d 'x' -f 2

分别得到寬和高

不過要是在java中通過runtime來運作這個指令是很麻煩的,它使用空格把參數分割出來的,它不會認為引号引起來的是一個參數,這個也有解決辦法,這裡就不說了。

是以,還是用identify test.png這個指令,得到的字元串用java的方式處理一下,也很簡單。

1、壓縮一個圖檔,限定高度為60, 寬高比例不變,但如果寬大于90,截取中間一段

convert source.jpg -resize x60 result_60.jpg

擷取result_60.jpg的寬和高

if( 寬 > 90 ){

    convert result_60.jpg -gravity center -extent 90x60 result_60.jpg

}

這裡要注意, -gravity和-extent配合使用在6.2.8的版本中是不正常的,可以選擇用crop

計算 dx = (寬-90)/2

convert result_60.jpg -crop 90x60+${dx}+0 result_60.jpg

2、壓縮一個圖檔,限定高和寬, 寬高比例不變,需要适當的裁減

例如:壓縮為60x60, 這是一個特例,寬高正好相同,如果不同,計算會有所不同,但方法一樣。

擷取source.jpg的寬和高

if( 寬 > 高 ){

  convert source.jpg -resize x60 -gravity center -extent 60x60 result_60.jpg

else{

  convert source.jpg -resize 60x -gravity center -extent 60x60 result_60.jpg

3、截圖

convert result_60.jpg -crop wxh+dx+dy result_60.jpg

w為要截取圖檔的寬

h為要截取圖檔的高

dx,dy是開始截取的偏移位置,以左上角為原點

4、拼圖

橫向拼接

convert 1.jpg 2.jpg 3.jpg +append result.jpg

縱向拼接

convert 1.jpg 2.jpg 3.jpg -append result.jpg

橫向+縱向

<code>convert /( 1.jpg 2.jpg 3.jpg +append /) / /( 4.jpg 5.jpg 6.jpg +append /) / /( 7.jpg 8.jpg 9.jpg +append /) / -append result.jpg 5、256色png壓縮 convert -strip -depth 8 -colors 256 soure.png result.png advpng -z -4 result.png 6、圖檔上寫字 convert source.jpg -font xxx.ttf -fill red -pointsize 48 -annotate +50+50 @text.txt result.jpg 使用字型xxx.ttf, 字型用紅色填充,字型48pixel, 位置(50,50), 文字在text.txt檔案中 7、圖檔上畫長方形 convert source.jpg fill none -stroke red -strokewidth 3 -draw rectangle 50,50 100,100 result.jpg 還一個線寬為3,顔色為紅色,從50,50到100,100的正方形,不填充 畫線為 -draw line 50,50 100,100  相關連結:</code>