- static public BufferedImage fromStream(InputStream in) throws IOException {
- MarkableFileInputStream tmpIn = null;
- File tmp = null;
-
- boolean resetable = in.markSupported();
- if (resetable) {
- try {
- in.reset();
- } catch (IOException e) {
- resetable = false;
- }
- }
-
- if (resetable) {
- return fromResetableStream(in);
- }
-
- tmp = File.createTempFile(".tmp-image", ".tmp");
- try {
- IOUtils.write(in, tmp);
- tmpIn = new MarkableFileInputStream(new FileInputStream(tmp));
- return fromResetableStream(tmpIn);
- } finally {
- try {
- if (tmpIn != null) {
- tmpIn.close();
- }
- } finally {
- tmp.delete();
- }
- }
- }
-
- /**
- * Convert the given resetable {@link InputStream} into an {@link Image}
- * object, respecting the EXIF transformations if any.
- *
- * @param in
- * the 'resetable' (this is mandatory) {@link InputStream}
- *
- * @return the {@link Image} object
- *
- * @throws IOException
- * in case of IO error
- */
- static private BufferedImage fromResetableStream(InputStream in)
- throws IOException {
-
- int orientation;
- try {
- orientation = getExifTransorm(in);
- } catch (Exception e) {
- // no EXIF transform, ok
- orientation = -1;
- }
-
- in.reset();
- BufferedImage image = ImageIO.read(in);
-
- if (image == null) {
- throw new IOException("Failed to convert input to image");
- }
-
- // Note: this code has been found on Internet;
- // thank you anonymous coder.
- int width = image.getWidth();
- int height = image.getHeight();
- AffineTransform affineTransform = new AffineTransform();
-
- switch (orientation) {
- case 1:
- affineTransform = null;
- break;
- case 2: // Flip X
- affineTransform.scale(-1.0, 1.0);
- affineTransform.translate(-width, 0);
- break;
- case 3: // PI rotation
- affineTransform.translate(width, height);
- affineTransform.rotate(Math.PI);
- break;
- case 4: // Flip Y
- affineTransform.scale(1.0, -1.0);
- affineTransform.translate(0, -height);
- break;
- case 5: // - PI/2 and Flip X
- affineTransform.rotate(-Math.PI / 2);
- affineTransform.scale(-1.0, 1.0);
- break;
- case 6: // -PI/2 and -width
- affineTransform.translate(height, 0);
- affineTransform.rotate(Math.PI / 2);
- break;
- case 7: // PI/2 and Flip
- affineTransform.scale(-1.0, 1.0);
- affineTransform.translate(-height, 0);
- affineTransform.translate(0, width);
- affineTransform.rotate(3 * Math.PI / 2);
- break;
- case 8: // PI / 2
- affineTransform.translate(0, width);
- affineTransform.rotate(3 * Math.PI / 2);
- break;
- default:
- affineTransform = null;
- break;
- }
-
- if (affineTransform != null) {
- AffineTransformOp affineTransformOp = new AffineTransformOp(
- affineTransform, AffineTransformOp.TYPE_BILINEAR);
-
- BufferedImage transformedImage = new BufferedImage(width, height,
- image.getType());
- transformedImage = affineTransformOp
- .filter(image, transformedImage);
-
- image = transformedImage;
- }
- //
-
- return image;
- }