所以我一直在发帖,但还没有得到一个可靠的答案:
我创建了一个带有裁剪方法的图像大小调整类。种植效果很好。我遇到的问题是我在drawImage
函数中指定的背景颜色Graphics
无法正常工作。无论我提供什么(在这种情况下Color.WHITE
),它默认为黑色作为背景。
此外,覆盖图像或最上面的图像(来自文件)正在反转(我认为是)或以其他方式变色。只是为了让您可以更好地概念化这一点,我正在拍摄一个 jpeg 并将其覆盖在一个新BufferedImage
的顶部,新的缓冲图像的背景没有被设置。这是我正在使用的以下代码:
public void Crop(int Height, int Width, int SourceX, int SourceY) throws Exception {
//output height and width
int OutputWidth = this.OutputImage.getWidth();
int OutputHeight = this.OutputImage.getHeight();
//create output streams
ByteArrayOutputStream MyByteArrayOutputStream = new ByteArrayOutputStream();
MemoryCacheImageOutputStream MyMemoryCacheImageOutputStream = new MemoryCacheImageOutputStream(MyByteArrayOutputStream);
//Create a new BufferedImage
BufferedImage NewImage = new BufferedImage(Width, Height, BufferedImage.TYPE_INT_RGB);
Graphics MyGraphics = NewImage.createGraphics();
MyGraphics.drawImage(this.OutputImage, -SourceX, -SourceY, OutputWidth, OutputHeight, Color.WHITE, null);
// Get Writer and set compression
Iterator MyIterator = ImageIO.getImageWritersByFormatName("png");
if (MyIterator.hasNext()) {
//get image writer
ImageWriter MyImageWriter = (ImageWriter)MyIterator.next();
//get params
ImageWriteParam MyImageWriteParam = MyImageWriter.getDefaultWriteParam();
//set outputstream
MyImageWriter.setOutput(MyMemoryCacheImageOutputStream);
//create new ioimage
IIOImage MyIIOImage = new IIOImage(NewImage, null, null);
//write new image
MyImageWriter.write(null, MyIIOImage, MyImageWriteParam);
}
//convert output stream back to inputstream
ByteArrayInputStream MyByteArrayInputStream = new ByteArrayInputStream(MyByteArrayOutputStream.toByteArray());
MemoryCacheImageInputStream MyMemoryCacheImageInputStream = new MemoryCacheImageInputStream(MyByteArrayInputStream);
//resassign as a buffered image
this.OutputImage = ImageIO.read(MyMemoryCacheImageInputStream);
}