import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.Iterator; import javax.imageio.ImageIO; import javax.imageio.ImageReadParam; import javax.imageio.ImageReader; import javax.imageio.stream.ImageInputStream; public class test { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub String qrcode; try { //java的urldecode会指定编码,需要设置为iso-8859-1,这样输出的才是二进制 qrcode = URLDecoder .decode("%89PNG%0D%0Axxxxxx", "ISO-8859-1"); //以下为二进制内容输出为图片,不可以直接用普通方式输出图片,会导致文件头加了些东西,导致图片破坏 ByteArrayInputStream bis = new ByteArrayInputStream( qrcode.getBytes()); Iterator<?> readers = ImageIO.getImageReadersByFormatName("png"); // ImageIO is a class containing static convenience methods for // locating ImageReaders // and ImageWriters, and performing simple encoding and decoding. ImageReader reader = (ImageReader) readers.next(); Object source = bis; // File or InputStream, it seems file is OK ImageInputStream iis = ImageIO.createImageInputStream(source); // Returns an ImageInputStream that will take its input from the // given Object reader.setInput(iis, true); ImageReadParam param = reader.getDefaultReadParam(); Image image = reader.read(0, param); // got an image file BufferedImage bufferedImage = new BufferedImage( image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_RGB); // bufferedImage is the RenderedImage to be written Graphics2D g2 = bufferedImage.createGraphics(); g2.drawImage(image, null, null); File imageFile = new File("d://test.png"); ImageIO.write(bufferedImage, "png", imageFile); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }