1 48 49 package org.jfree.chart.encoders; 50 51 import java.awt.image.BufferedImage ; 52 import java.io.ByteArrayOutputStream ; 53 import java.io.IOException ; 54 import java.io.OutputStream ; 55 import java.util.Iterator ; 56 57 import javax.imageio.IIOImage ; 58 import javax.imageio.ImageIO ; 59 import javax.imageio.ImageWriteParam ; 60 import javax.imageio.ImageWriter ; 61 import javax.imageio.stream.ImageOutputStream ; 62 63 68 public class SunJPEGEncoderAdapter implements ImageEncoder { 69 70 71 private float quality = 0.95f; 72 73 76 public SunJPEGEncoderAdapter() { 77 } 78 79 88 public float getQuality() { 89 return this.quality; 90 } 91 92 100 public void setQuality(float quality) { 101 if (quality < 0.0f || quality > 1.0f) { 102 throw new IllegalArgumentException ( 103 "The 'quality' must be in the range 0.0f to 1.0f"); 104 } 105 this.quality = quality; 106 } 107 108 114 public boolean isEncodingAlpha() { 115 return false; 116 } 117 118 124 public void setEncodingAlpha(boolean encodingAlpha) { 125 } 127 128 140 public byte[] encode(BufferedImage bufferedImage) throws IOException { 141 ByteArrayOutputStream outputStream = new ByteArrayOutputStream (); 142 encode(bufferedImage, outputStream); 143 return outputStream.toByteArray(); 144 } 145 146 158 public void encode(BufferedImage bufferedImage, OutputStream outputStream) 159 throws IOException { 160 if (bufferedImage == null) { 161 throw new IllegalArgumentException ("Null 'image' argument."); 162 } 163 if (outputStream == null) { 164 throw new IllegalArgumentException ("Null 'outputStream' argument."); 165 } 166 Iterator iterator = ImageIO.getImageWritersByFormatName("jpeg"); 167 ImageWriter writer = (ImageWriter ) iterator.next(); 168 ImageWriteParam p = writer.getDefaultWriteParam(); 169 p.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); 170 p.setCompressionQuality(this.quality); 171 ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream); 172 writer.setOutput(ios); 173 writer.write(null, new IIOImage (bufferedImage, null, null), p); 174 ios.flush(); 175 writer.dispose(); 176 ios.close(); 177 } 178 179 } 180 | Popular Tags |