簡體   English   中英

如何在 scala/java 中將圖像裁剪為 svg/png 蒙版的形狀

[英]How can I crop an image to the shape of a svg/png mask in scala/java

假設我有一個 Z 形白色蒙版,我想將圖像裁剪成這個形狀。 如何在 java 中做到這一點?

兩個圖像都是 2560x1440,但 Z 形掩碼具有透明位。

我在 scala 中的嘗試,但使用了 Java 的 awt 庫:

val imageBuff = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
val imageB = imageBuff.createGraphics()
imageB.drawImage(image, 0, 0, null)

val maskBuffered = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
val maskB = mask01Buffered.createGraphics()
maskB.drawImage(scaledmask, 0, 0, null)


def applyMask(imageBuffered: BufferedImage, maskBuffered: BufferedImage): BufferedImage = {
  val imagePixels = heroBuffered.getRGB(0, 0, width, height, null, 0, width)
  val maskPixels = maskBuffered.getRGB(0, 0, width, height, null, 0, width)

 for (i <- 0 to maskPixels.length - 1)
  {
    val color = imagePixels(i)
    val mask = maskPixels(i) 
    imagePixels(i) = mask | color
  }

  imageBuffered.setRGB(0, 0, width, height, imagePixels, 0, width)
  imageBuffered
}

val maskApplied = applyMask(imageBuff, maskBuffered)

val scaledForeground: Image = maskApplied.getScaledInstance((width * 1.08).toInt, (height * 1.08).toInt, Image.SCALE_DEFAULT)

val finalImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB)
val f = finalImage.createGraphics
val newX: Int = (0 - width * 0.08).toInt
val newY: Int = (0 - height * 0.08).toInt
f.drawImage(scaledForeground, newX, newY, null)

ImageIO.write(finalImage, "jpeg", new FileOutputStream(imagePath.takeWhile(_.toString != ".") + "-" + keyline.name + "-final-image.jpeg"))
f.dispose()

這將創建一個圖像,其中我通過 z 形狀的一小部分顯示原始圖像,但我想剝離蒙版透明的任何東西。

有沒有人有任何其他想法?

非常感謝,J

我設法弄清楚了這一點。 訣竅在於 for 循環。

它需要更像這樣:

for (i <- 0 to heroPixels.length - 1)
  {
    val color = heroPixels(i)
    val mask = maskPixels(i)

    if (mask == whiteInt) {
      heroPixels(i) = color
    } else
      heroPixels(i) = new Color(0,0,0, 1).getRGB
  }

然后使用BufferedImage.TYPE_INT_ARGB而不是BufferedImage.TYPE_INT_RGB

暫無
暫無

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

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