Home > Java > javaTutorial > Detailed explanation of Java using ImageIO.writer to generate jpeg images from BufferedImage, summary and solutions to problems encountered

Detailed explanation of Java using ImageIO.writer to generate jpeg images from BufferedImage, summary and solutions to problems encountered

黄舟
Release: 2017-03-25 10:42:49
Original
4183 people have browsed it

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();  
  }
Copy after login

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

Detailed explanation of Java using ImageIO.writer to generate jpeg images from BufferedImage, summary and solutions to problems encountered

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();    
  }
Copy after login

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();    
  }
Copy after login

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

searched from the Internet. Most of the image formats encountered are jpeg, but there are also a small number of png, bmp and other formats. For the vast majority of jpeg images, my initial method is effective, but the above method seems a bit redundant and wastes resources because it requires one more step. , so the above method has been improved. The basic principle is to first try to directly ImageIO.write to generate jpeg. If it fails, use the second method.

  /**
   * 将{@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();    
  }
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template