0

I am reading a image file in a servlet from an http request. I want to crop it as a square and write it to file. I can achieve that with the following code but i am using a temporary file to write the original image first. How can I do that without using a temp file

                    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();
Nuri Tasdemir
  • 9,720
  • 3
  • 42
  • 67

2 Answers2

0

You cannot crop a BufferedImage without creating a new BufferedImage as a side effect

CodeGuy
  • 28,427
  • 76
  • 200
  • 317
0

I solved it using ByteArray.

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

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

And I used this link in the process http://www.mkyong.com/java/how-to-convert-byte-to-bufferedimage-in-java/

Nuri Tasdemir
  • 9,720
  • 3
  • 42
  • 67