java - 使用 BufferedImage 生成缩略图,无需反转颜色并在 Java 中获得 alpha

标签 java graphics

我使用“BufferedImage”通过此代码生成缩略图。

try {
 BufferedImage bi = new BufferedImage(thumWidth, thumHeight, TYPE_INT_ARGB);
 Graphics2D g = bi.createGraphics();

 Image ii = (new ImageIcon(orgFile.getAbsolutePath())).getImage();

 g.drawImage(ii, 0, 0, thumWidth, thumHeight, null);
 String thumbFileDir = prefixPath + "/" + thumWidth + "/" + afterPath;
 File file = this.createPathIfnotexist(thumbFileDir);
 String fullPathToSave = this.genPath(file.getAbsolutePath(), fileName);
 File thumbFile = new File(fullPathToSave);
 ImageIO.write(bi, ext, thumbFile);
} catch (IOException var22) {
 var22.printStackTrace();
 return;
} catch (Exception var23) {
 var23.printStackTrace();
}

我的问题是...

  1. 当我使用 TYPE_INT_RGB 获取 BufferedImage 实例时,发送 PNG 文件时会丢失 alpha,而发送 JPG 文件时则没问题。 Original , Converted

  2. 当我使用TYPE_INT_ARGB获取BufferedImage的实例时,发送PNG文件时获得alpha,但发送JPG文件时颜色相反。 Original , Converted

所以,我想创建缩略图而不反转颜色并保持 Alpha。我该怎么办?

最佳答案

根据我不断研究的结果,我认为使用外部库比按照问题中建议的方式尝试更方便。

所以,我决定使用 java-image-scaling生成缩略图。

对于那些将来访问此页面的人,我留下了一些代码。 (其实问题是用Java写的,但答案是用Kotlin写的。)

imgLocation为原图上传路径,width为引用点,如100、240、480、720、1080。

    private val rootLocation: Path by lazy { Paths.get(location) }
    private val formatNames = ImageIO.getWriterFormatNames().toList()

    override fun resizeImage(imgLocation: String, width: Int): File {
        val originFile = this.rootLocation.resolve(imgLocation).toFile()
        val destFile = this.rootLocation.resolve("resized-$width-${originFile.name}").toFile()

        val bufferedImage: BufferedImage = originFile.inputStream().use { ImageIO.read(it) }
        val resizeImage = if (width <= bufferedImage.width) {
            val nHeight = width * bufferedImage.height / bufferedImage.width
            val rescale = MultiStepRescaleOp(width, nHeight).apply { unsharpenMask = AdvancedResizeOp.UnsharpenMask.Soft }
            rescale.filter(bufferedImage, null)
        } else {
            bufferedImage
        }

        val target = if (formatNames.contains(destFile.extension)) destFile else File(destFile.path + ".jpg")
        ImageIO.write(resizeImage, target.extension, target)

        bufferedImage.flush()
        return destFile
    }

关于java - 使用 BufferedImage 生成缩略图,无需反转颜色并在 Java 中获得 alpha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54898593/

相关文章:

java - 调用java方法绘制图形

graphics - 我想要没有堆栈且没有递归的Flood Fill

java - 由 : org. hsqldb.HsqlException 引起:无效的 statemnet - 导入 CSV 数据时需要文本表

java - hibernate 中的多对一连接

java - 具有两个不同顶点的 JUNG 图

雷达图外围标签截止

java - 相当于 Java Servlet 的 PHP

java - 身份方法做什么,通用单例java

java - 拉格朗日松弛 Cplex 和 Java

graphics - 如何将此 HLSL 像素着色器校正为四边形的圆角?