首页 > 解决方案 > Graphics2D 中的叠加图像

问题描述

那里!如何使用 Graphics2D drawImage 方法通过坐标叠加图像。我在 X,Y 中有 4 个点坐标。我需要在给定的坐标内绘制图像。你能给出一些提示或其他方法来实现吗?

  private fun addImageBlur(output: BufferedImage, dto: BlurPhotoBox): BufferedImage {
    val outputFile = output
    try {
        val osOutput = ByteArrayOutputStream()
        var blur = ImageIO.read(URL("/images/plateWatermark.png"))
        blur = Scalr.resize(blur, Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_TO_WIDTH, outputFile?.width!! / if (outputFile.height > outputFile.width) 3 else 5)

        // initializes necessary graphic properties
        val g2d: Graphics2D = outputFile.graphics as Graphics2D
        val alphaChannel: AlphaComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f)
        g2d.setComposite(alphaChannel)

        g2d.drawImage(blur, dto.x1, dto.y1, null)
        g2d.drawImage(blur, dto.x1, dto.y1, dto.x2, dto.y2, dto.x3, dto.y3, dto.x4, dto.y4, null)

        g2d.drawPolygon(arrayOf(dto.x1, dto.x2, dto.x3, dto.x4).toIntArray(), arrayOf(dto.y1, dto.y2, dto.y3, dto.y4).toIntArray(), 4)
        g2d.color = java.awt.Color.RED
        g2d.fillPolygon(arrayOf(dto.x1, dto.x2, dto.x3, dto.x4).toIntArray(), arrayOf(dto.y1, dto.y2, dto.y3, dto.y4).toIntArray(), 4)
        g2d.dispose()
    } catch (ex: IOException) {
        System.err.println(ex)
    }
    return outputFile
}

坐标示例:

  "box" : {
    "x1": 150,
    "x2": 325,
    "x3": 325,
    "x4": 150,
    
    "y1": 1073, 
    "y2": 993,        
    "y3": 1048,    
    "y4": 1123    
}

标签: javakotlingraphics2d

解决方案


推荐阅读