


Detailed explanation of Java using ImageIO.writer to generate jpeg images from BufferedImage, summary and solutions to problems encountered
This article mainly introduces the relevant information on the summary and solution of problems encountered in generating jpeg images from BufferedImage using ImageIO.writer in java. Friends in need can refer to the following
java Using ImageIO.writer to generate jpeg images from BufferedImage Summary and solutions to problems encountered when BufferedImage generates jpeg images
Generating jpeg images is a very, very simple thing. Many introductions on the Internet use com.sun.image.codec.jpeg directly. JPEGImageEncoder is implemented as follows:
/** * 将原图压缩生成jpeg格式的数据 * @param source * @return */ public static byte[] wirteJPEGBytes(BufferedImage source){ if(null==source) throw new NullPointerException(); ByteArrayOutputStream output = new ByteArrayOutputStream(); JPEGImageEncoder jencoder = JPEGCodec.createJPEGEncoder(output); JPEGEncodeParam param = jencoder.getDefaultJPEGEncodeParam(source); param.setQuality(0.75f, true); jencoder.setJPEGEncodeParam(param); try { jencoder.encode(source); } catch (ImageFormatException e) { throw new RuntimeException(e); } catch (IOException e) { throw new RuntimeException(e); } return output.toByteArray(); }
JPEGImageEncoder is just sun’s jpeg encoding implementation. It is not a standard Java API. It is only supported in sun jvm, but will not be used on other jvm. support.
Also, although the above code can be executed normally on Java 1.6 and 1.7, if you use java 1.8, the above code will report an error:
Access restrictions: Due to The required library C:\Program Files\Java\jdk1.8.0_111\jre\lib\rt.jar has certain restrictions and therefore cannot access type JPEGImageEncoder
So this method has limitations.
It is not possible to take shortcuts. You still have to follow the Java specifications. The ImageIO class provides the ImageIO.writer method to generate images in the specified format. This is the formal implementation method. .
But there are also some considerations when using the ImageIO.writer method.
I originally wrote it like this, which is to simply call the ImageIO.writer method to generate jpeg data:
/** * 将原图压缩生成jpeg格式的数据 * @param source * @return * @see #wirteBytes(BufferedImage, String) */ public static byte[] wirteJPEGBytes(BufferedImage source){ return wirteBytes(source,"JPEG"); } /** * 将原图压缩生成jpeg格式的数据 * @param source * @return * @see #wirteBytes(BufferedImage, String) */ public static byte[] wirteJPEGBytes(BufferedImage source){ return wirteBytes(source,"JPEG"); } /** * 将{@link BufferedImage}生成formatName指定格式的图像数据 * @param source * @param formatName 图像格式名,图像格式名错误则抛出异常 * @return */ public static byte[] wirteBytes(BufferedImage source,String formatName){ Assert.notNull(source, "source"); Assert.notEmpty(formatName, "formatName"); ByteArrayOutputStream output = new ByteArrayOutputStream(); try { if(!ImageIO.write(source, formatName.toLowerCase(), output)) // 返回false则抛出异常 throw new IllegalArgumentException(String.format("not found writer for '%s'",formatName)); } catch (IOException e) { throw new RuntimeException(e); } return output.toByteArray(); }
It has no problem processing tens of thousands of image files. When I encounter one png image, ImageIO.write actually returned false and threw an exception.
The reason is that when the private method getWriter called by the ImageIO.wite method looks for a suitable ImageWriter, it is not only related to the formatName, but also to the input original image (specifically how it is related, because the logic The relationship is too complicated and has not been studied in depth), causing the getWriter method to not be able to find the corresponding ImageWriter.
Refer to other people’s writing methods on the Internet and change it to this, no problem:
/** * 将{@link BufferedImage}生成formatName指定格式的图像数据 * @param source * @param formatName 图像格式名,图像格式名错误则抛出异常 * @return */ public static byte[] wirteBytes(BufferedImage source,String formatName){ Assert.notNull(source, "source"); Assert.notEmpty(formatName, "formatName"); ByteArrayOutputStream output = new ByteArrayOutputStream(); BufferedImage newBufferedImage = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g = newBufferedImage.createGraphics(); try { g.drawImage(source, 0, 0,null); if(!ImageIO.write(newBufferedImage, formatName, output)) throw new IllegalArgumentException(String.format("not found writer for '%s'",formatName)); } catch (IOException e) { throw new RuntimeException(e); }finally{ g.dispose(); } return output.toByteArray(); }
The basic idea is to recreate a BufferedImage of the same size, and then use the Graphics.drawImage method to draw the original image Write a new BufferedImage object. Through this conversion, the differences between BufferedImage objects generated by different types of image formats are smoothed out, and then call ImageIO.write to ## the new ImageIO.write object. #Image processing There will be no problem.
Improvement
In my project, the image data is/** * 将{@link BufferedImage}生成formatName指定格式的图像数据 * @param source * @param formatName 图像格式名,图像格式名错误则抛出异常 * @return */ public static byte[] wirteBytes(BufferedImage source,String formatName){ Assert.notNull(source, "source"); Assert.notEmpty(formatName, "formatName"); ByteArrayOutputStream output = new ByteArrayOutputStream(); Graphics2D g = null; try { for(BufferedImage s=source;!ImageIO.write(s, formatName, output);){ if(null!=g) throw new IllegalArgumentException(String.format("not found writer for '%s'",formatName)); s = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_RGB); g = s.createGraphics(); g.drawImage(source, 0, 0,null); } } catch (IOException e) { throw new RuntimeException(e); } finally { if (null != g) g.dispose(); } return output.toByteArray(); }
The above is the detailed content of Detailed explanation of Java using ImageIO.writer to generate jpeg images from BufferedImage, summary and solutions to problems encountered. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Guide to Square Root in Java. Here we discuss how Square Root works in Java with example and its code implementation respectively.

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Random Number Generator in Java. Here we discuss Functions in Java with examples and two different Generators with ther examples.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to the Armstrong Number in Java. Here we discuss an introduction to Armstrong's number in java along with some of the code.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is
