0

我正在从 http 请求中读取 servlet 中的图像文件。我想将其裁剪为正方形并将其写入文件。我可以使用以下代码实现这一点,但我使用临时文件先写入原始图像。如何在不使用临时文件的情况下做到这一点

                    File tempFile = new File(saveFileFrameTemp);
                    fileOut = new FileOutputStream(tempFile);
                    fileOut.write(dataBytes, startPos, (endPos - startPos));
                    fileOut.flush();
                    fileOut.close();

                    BufferedImage fullFrame = ImageIO.read(tempFile);
                    int height = fullFrame.getHeight();
                    int width = fullFrame.getWidth();
                    if (height > width)
                        ImageIO.write( fullFrame.getSubimage(0, (height-width)/2, width, width), "jpg", new File(saveFileFrame));
                    else
                        ImageIO.write( fullFrame.getSubimage((width-height)/2, 0, height, height), "jpg", new File(saveFileFrame));

                    tempFile.delete();
4

2 回答 2

0

如果不创建新的 BufferedImage 作为副作用,则无法裁剪 BufferedImage

于 2013-04-01T17:22:54.940 回答
0

我使用 ByteArray 解决了它。

ByteArrayOutputStream baos = new ByteArrayOutputStream();
baos.write(dataBytes, startPos, (endPos - startPos));

BufferedImage fullFrame = ImageIO.read(new ByteArrayInputStream(baos.toByteArray()));

我在这个过程中使用了这个链接http://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/

于 2013-04-01T18:29:13.380 回答