Small image cropping Problems
An error occurred while cropping Images Using ImageIO today:
Not a JPEG file: starts with 0xff 0xd9
To get the crop origin and crop size, I want to get the image width and height, and use a smaller image as the crop size to get a square image. The following code is available:
File imageFile = new File (imageFileFullPath); FileInputStream imageFileInputStream = new FileInputStream (imageFile); // obtain the original image, used to read the width and height BufferedImage bufferedImage = ImageIO. read (imageFileInputStream); int imageWidth = bufferedImage. getWidth (); int imageHeight = bufferedImage. getHeight (); if (imageWidth = imageHeight) {// return directly without cropping} // take the smaller value as the cropping size int clipSize = imageWidth> imageHeight? ImageHeight: imageWidth;
However, this code is used when cropping and outputting results:
Iterator <ImageReader> readerIt = ImageIO. getImageReadersByFormatName ("jpg"); ImageReader reader = readerIt. next (); // obtain the image stream ImageInputStream imageInputStream = ImageIO. createImageInputStream (imageFileInputStream); reader. setInput (imageInputStream, true); Rectangle rectangle = new Rectangle (0, 0, clipSize, clipSize); param. setSourceRegion (rectangle); // read the selected region BufferedImage clipedImage = reader. read (0, param );
It wasn't long before I found a solution, so I thought the cause of the error was to define two bufferedimages. The solution is to remove the definition of the BufferedImage object for obtaining the width and height, and use reader to get the original image size:
int imageWidth = reader.getWidth(0);int imageHeight = reader.getHeight(0);
In this way, the system can run normally. I still cannot understand how the errors mentioned at the beginning of the article appear, because the definition of BufferedImage can be removed, so I wonder if I cannot define two BufferedImage objects until I try the following methods:
BufferedImage clipedImage = bufferedImage.getSubimage(0, 0, clipSize, clipSize);
Instead of the above Code, two BufferedImage objects are also used, which can be executed well.
Afterwards, I continued to think about the possible cause of this error and found a suspicious cause:
// Obtain the original image, used to read the width and height BufferedImage bufferedImage = ImageIO. read (imageFileInputStream );
This imageFileInputStream object is an image object that has been read, and another parameter of ImageIO's read method is File, so I replaced it:
BufferedImage bufferedImage = ImageIO.read(imageFile);
The cropping was successful! However, I still did not fundamentally understand the cause of the error. I will keep it down for the moment, and I will find it later.
For the image cropping code, see:
Http://www.oschina.net/code/snippet_857368_14826
Paste a good message about BufferedImage:
Http://blog.163.com/yuhua_kui/blog/static/9679964420139118203818/