i使用'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();
}
我的问题是...
当我通过
TYPE_INT_RGB
获得BufferedImage实例时,发送PNG文件时会丢失Alpha,并且在发送JPG文件时很好。原始,转换当我使用
TYPE_INT_ARGB
获得BufferedImage实例时,发送PNG文件时会获得Alpha,但是在发送JPG文件时颜色是倒数的。原始,转换
所以,我想创建缩略图而不反转颜色并保持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
}