簡體   English   中英

imagemagick:將一張圖像裁剪為四個不相等大小的部分,但保持原始 canvas 大小和繪制背景透明

[英]imagemagick: crop one image to four not equal size parts, but but keep original canvas size and paint background transparent

我有一個 1920X1920 比例的圖像,如下所示: 原始圖像

我想裁剪這個原始圖像,使其分為四個部分。 在此處輸入圖像描述 最終形成四張圖片的效果,每張都是原尺寸。 在此處輸入圖像描述

我用過這樣的命令,但是這個智能forms上下兩張圖,不能組成四張透明圖

convert lena.png -crop 1x2@ +adjoin lena_%02d.miff
for img in *.miff; do
name=$(convert $img -format %t info:)
convert $img -background transparent -flatten $name.png
done
rm -f *.miff

請問,有沒有很優雅的方法可以達到我夢寐以求的效果?

如果沒有實際的圖像和尺寸,很難正確回答您,但讓我們嘗試讓您到達那里。

我們將制作 4 張圖像並將它們發送到montage以制作 4 張圖像蒙太奇,布局為 2 行和 2 列:

magick -size 240x120              \
    xc:red  -write miff:- +delete \
    xc:lime -write miff:- +delete \
    xc:blue -write miff:- +delete \
    xc:black miff:- | magick montage -background yellow -geometry +10+10 miff:- result.png

希望所有不同的顏色和背景都能讓你看到它在做什么。


現在,我們不會發送 4 個純色塊,而是

  • 裁剪出你想要的部分——我的數字是錯誤的,但你應該看看它們是如何工作的,
  • 設置重力,使它們在正確的方向延伸,
  • 擴展它們,並且
  • 將它們發送到最終的montage命令進行組裝 - 完全如上所示。

magick YOURIMAGE \
   \( +clone -crop 200x100+10+10   -gravity northwest -background red -extent 300x200 -write miff:- +delete \) \
   \( +clone -crop 200x100+200+10  -gravity northeast -background lime -extent 300x200 -write miff:- +delete \) \
   \( +clone -crop 200x100+10+100  -gravity southwest -background blue -extent 300x200 -write miff:- +delete \) \
             -crop 200x100+200+100 -gravity southeast -background black -extent 300x200 -write miff:- | magick montage ...

練習自己裁剪圖像的一部分,設置重力和背景,然后擴展和保存:

magick YOURIMAGE -crop 200x100+20+40 -gravity southeast -background cyan -extend 800x400 result.png

注意:由於您可能正在使用的圖像不是您發布的圖像,因此您需要修改此代碼以適合您的目的。

#!/bin/bash

width=$(convert lena.png -format "%w" info:)
height=$(convert lena.png -format "%h" info:)

# Get the Percentage of the Width
pct_w() {
  echo $(($1*$width/100))
}

# Get the Percentage of the Height
pct_h() {
  echo $(($1*$height/100))
}

# Top-Left
convert lena.png -crop $(pct_w 33)x$(pct_h 50)+0+0 +adjoin top-left.miff
convert top-left.miff -background transparent -flatten top-left.png

# Top-Right
convert lena.png -crop $(pct_w 66)x$(pct_h 50)+$(pct_w 33)+0 +adjoin top-right.miff
convert top-right.miff -background transparent -flatten top-right.png

# Bottom-Left
convert lena.png -crop $(pct_w 65)x$(pct_h 50)+0+$(pct_h 50) +adjoin bottom-left.miff
convert bottom-left.miff -background transparent -flatten bottom-left.png

# Bottom-Right
convert lena.png -crop $(pct_w 35)x$(pct_h 50)+$(pct_w 65)+$(pct_h 50) +adjoin bottom-right.miff
convert bottom-right.miff -background transparent -flatten bottom-right.png

rm *.miff

有兩個輔助函數來計算寬度和高度的百分比。 在代碼$(pct_w 33)中,這指的是寬度的 33%。 相應地更改這些值,直到獲得所需的削減。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM