注册 登录  
 加关注
查看详情
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

装甲步兵

迎春故早发,独自不疑寒。 畏落众花后,无人别意看。

 
 
 

日志

 
 
关于我

欢迎各位朋友加好友,共同交流进步!欢迎讨论编程技术(c/c++,java) 搜索引擎技术 互联网舆情监测技术 历史

java 图片压缩  

2012-09-28 09:22:48|  分类: JAVA |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

java 图片压缩

package test;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import javax.swing.ImageIcon;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
 
 
public class ImageSizer {  
    public static final MediaTracker tracker = new MediaTracker(new Component() {  
        private static final long serialVersionUID = 1234162663955668507L;}   
    );  
     
    public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException {  
       if(format!=null && "gif".equals(format.toLowerCase())){  
           resize(originalFile, resizedFile, width, 1);  
           return;  
       
        FileInputStream fis = new FileInputStream(originalFile);  
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();  
        int readLength = -1;  
        int bufferSize = 1024;  
        byte bytes[] = new byte[bufferSize];  
        while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {  
            byteStream.write(bytes, 0, readLength);  
        
       byte[] in = byteStream.toByteArray();  
        fis.close();  
        byteStream.close();  
         
       Image inputImage = Toolkit.getDefaultToolkit().createImage( in );  
        waitForImage( inputImage );  
        int imageWidth = inputImage.getWidth( null );  
       if ( imageWidth < 1 )   
           throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );  
        int imageHeight = inputImage.getHeight( null );  
        if ( imageHeight < 1 )   
           throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );  
          
        // Create output image.  
        int height = -1;  
        double scaleW = (double) imageWidth / (double) width;  
        double scaleY = (double) imageHeight / (double) height;  
        if (scaleW >= 0 && scaleY >=0) {  
            if (scaleW > scaleY) {  
                height = -1;  
            } else {  
                width = -1;  
            
        
        Image outputImage = inputImage.getScaledInstance( width, height, java.awt.Image.SCALE_DEFAULT);  
        checkImage( outputImage );          
       encode(new FileOutputStream(resizedFile), outputImage, format);          
        
 
     
    private static void checkImage( Image image ) {  
       waitForImage( image );  
       int imageWidth = image.getWidth( null );  
       if ( imageWidth < 1 )   
          throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );  
       int imageHeight = image.getHeight( null );  
       if ( imageHeight < 1 )   
         throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );  
    
 
     
    private static void waitForImage( Image image ) {  
       try {  
          tracker.addImage( image, 0 );  
          tracker.waitForID( 0 );  
          tracker.removeImage(image, 0);  
       } catch( InterruptedException e ) { e.printStackTrace(); }  
     
 
     
    private static void encode( OutputStream outputStream, Image outputImage, String format )   
       throws java.io.IOException {  
       int outputWidth  = outputImage.getWidth( null );  
       if ( outputWidth < 1 )   
          throw new IllegalArgumentException( "output image width " + outputWidth + " is out of range" );  
       int outputHeight = outputImage.getHeight( null );  
       if ( outputHeight < 1 )   
          throw new IllegalArgumentException( "output image height " + outputHeight + " is out of range" );  
 
       // Get a buffered image from the image.  
       BufferedImage bi = new BufferedImage( outputWidth, outputHeight,  
          BufferedImage.TYPE_INT_RGB );                                                     
       Graphics2D biContext = bi.createGraphics();  
       biContext.drawImage( outputImage, 0, 0, null );  
       ImageIO.write(bi, format, outputStream);  
       System.out.println("----the end ------");  
       outputStream.flush();    
       outputStream.close();  
     
      
     
    private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {  
        if (quality < 0 || quality > 1) {  
            throw new IllegalArgumentException("Quality has to be between 0 and 1");  
         
        ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());  
        Image i = ii.getImage();  
        Image resizedImage = null;   
        int iWidth = i.getWidth(null);  
        int iHeight = i.getHeight(null);   
        if (iWidth > iHeight) {  
            resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);  
        } else {  
            resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);  
         
        // This code ensures that all the pixels in the image are loaded.  
        Image temp = new ImageIcon(resizedImage).getImage();   
        // Create the buffered image.  
        BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),  
                                                        BufferedImage.TYPE_INT_RGB);   
        // Copy image to buffered image.  
        Graphics g = bufferedImage.createGraphics();   
        // Clear background and paint the image.  
        g.setColor(Color.white);  
        g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));  
        g.drawImage(temp, 0, 0, null);  
        g.dispose();   
        // Soften.  
        float softenFactor = 0.05f;  
        float[] softenArray = {0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0};  
        Kernel kernel = new Kernel(3, 3, softenArray);  
        ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);  
        bufferedImage = cOp.filter(bufferedImage, null);   
        // Write the jpeg to a file.  
        FileOutputStream out = new FileOutputStream(resizedFile);          
        // Encodes image as a JPEG data stream  
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);   
        param.setQuality(quality, true);   
        encoder.setJPEGEncodeParam(param);  
        encoder.encode(bufferedImage);  
    
   
   
    public static void main(String args[]) {

     
     File f = new File("D:\\Work\\Java\\Eclipse3.6Workspace\\prj_image\\images\\qier.png");

   
     long start = System.currentTimeMillis();
     System.out.println("开始时间: "+start);
     FileInputStream fs;
  try {
   fs = new FileInputStream(f);
   try {
    System.out.println("大小: "+fs.available()/1024);
   } catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  } catch (FileNotFoundException e1) {
   // TODO Auto-generated catch block
   e1.printStackTrace();
  }
  
      try {
         Iterator readers = ImageIO.getImageReadersByFormatName("png");
         ImageReader reader = (ImageReader)readers.next();
         ImageInputStream iis = ImageIO.createImageInputStream(f);
         reader.setInput(iis, true);
         System.out.println("width:"+reader.getWidth(0));
         System.out.println("height:"+reader.getHeight(0));
        } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
       
       
        long end = System.currentTimeMillis();
          System.out.println("结束时间: "+end);     
          System.out.println("耗时: "+(end-start));


    }
}

  评论这张
 
阅读(88)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2018