java图片压缩

来源:互联网 发布:伦敦金2016年历史数据 编辑:程序博客网 时间:2024/06/08 17:00
图片压缩分为无损有损压缩处理

首先考虑用开源的或商业的jar包。

1.thumbnailator-0.4.2-all.jar

2.图片压缩:magickimage 

Java图片处理/压缩:ImageMagick for java 使用Jmagick压缩高质量图片(包括Jmagick的应用)

ImageMagick for java 使用Jmagick压缩高质量图片j

在做pdf文档转成jpg的时候,发现了Jmagick的创建高质量的图片的一个java类库,自己以前使用另外的一个类库,感觉这个更好点,就试着用了下,感觉不错

1.使用的windows下的jmagick-win-6.3.9-Q16.zip 地址是:http://downloads.jmagick.org/6.3.9/

2.doc对应的api地址:http://downloads.jmagick.org/jmagick-doc/

3.安装ImageMagick,官方网站:http://www.imagemagick.org/

我使用的是:ImageMagick-6.4.6-4-Q16-windows-dll.exe :点击下载

4. 安装ImageMagick-6.4.6-4-Q16-windows-dll.exe,将 安装目录下(按自己所安装的目录找) 下的所有dll文件 copy 到系统盘下的 “C:\WINDOWS\system32\”文件夹里

5. 配置环境变量
再环境变量path里添加新的值 “C:\Program Files\ImageMagick-6.4.6-4-Q16“使用IDE可以不用配置

6.解压jmagick-win-6.3.9-Q16.zip
将 jmagick.dll 复制到系统盘下的 “C:\WINDOWS\system32\”文件夹里 和 复制到jdk的bin(例“D:\jdk6\bin”)文件里各一份
将 jmagick.jar 复制到Tomcat下的lib文件夹里 和 所使用项目的WEB-INF下lib文件里 各一份

7.web应用如果部署到tomcat下,那么最好在catalina.bat文件中改变如下设置
set JAVA_OPTS=%JAVA_OPTS% -Xms256M -Xmx768M -XX:MaxPermSize=128M – Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager – Djava.util.logging.config.file=”${catalina.base}\conf\logging.properties”
避免heap溢出的问题,参数看你自己的机器而定。( -Xms256M -Xmx768M -XX:MaxPermSize=128M )

8.还要注意如果部署到web应用,你在使用的class里面需要
System.setProperty(“jmagick.systemclassloader”,”no”);
要不然会报出UnsatisfiedLinkError: no JMagick in java.library.path.
实例测试code:

    
[java] view plaincopy
  1.     package com.utils;  
  2.    
  3. import magick.ImageInfo;  
  4. import magick.MagickApiException;  
  5. import magick.MagickException;  
  6. import magick.MagickImage;  
  7.    
  8. public class Treamspdf {  
  9.  public static void main(String[] args) {  
  10. resetsize("E:/mylearn/workspace/TTPDF/src/com/utils/http_imgload.jpg","new.jpg");  
  11. }  
  12.     public static void resetsize(String picFrom,String picTo){  
  13.         try{  
  14.             ImageInfo info=new ImageInfo(picFrom);  
  15.             MagickImage image=new MagickImage(new ImageInfo(picFrom));  
  16.             MagickImage scaled=image.scaleImage(12097);  
  17.             scaled.setFileName(picTo);  
  18.             scaled.writeImage(info);  
  19.         }catch(MagickApiException ex){  
  20.             ex.printStackTrace();  
  21.         } catch(MagickException   ex)   {  
  22.             ex.printStackTrace();  
  23.         }  
  24.     }  
  25. }  

常用的水印,切图,压缩等简单程序工具类,继续下面

[java] view plaincopy
  1. package com.utils;     
  2.    
  3. import java.awt.Dimension;  
  4. import java.awt.Rectangle;  
  5. import java.text.SimpleDateFormat;  
  6. import java.util.Date;     
  7.    
  8. import magick.CompositeOperator;  
  9. import magick.CompressionType;  
  10. import magick.DrawInfo;  
  11. import magick.ImageInfo;  
  12. import magick.MagickException;  
  13. import magick.MagickImage;  
  14. import magick.PixelPacket;  
  15. import magick.PreviewType;     
  16.    
  17. public class Aa {     
  18.    
  19.     static{  
  20.         //不能漏掉这个,不然jmagick.jar的路径找不到  
  21.         System.setProperty("jmagick.systemclassloader","no");  
  22.     }     
  23.    
  24.     /** 
  25.      * 压缩图片 
  26.      * @param filePath 源文件路径 
  27.      * @param toPath   缩略图路径 
  28.      */  
  29.     public static void createThumbnail(String filePath, String toPath) throws MagickException{  
  30.         ImageInfo info = null;  
  31.         MagickImage image = null;  
  32.         Dimension imageDim = null;  
  33.         MagickImage scaled = null;  
  34.         try{  
  35.             info = new ImageInfo(filePath);  
  36.             image = new MagickImage(info);  
  37.             imageDim = image.getDimension();  
  38.             int wideth = imageDim.width;  
  39.             int height = imageDim.height;  
  40.             if (wideth > height) {  
  41.                 height = 660 * height / wideth;  
  42.                 wideth = 660;  
  43.             }  
  44.             scaled = image.scaleImage(wideth, height);//小图片文件的大小.  
  45.             scaled.setFileName(toPath);  
  46.             scaled.writeImage(info);  
  47.         }finally{  
  48.             if(scaled != null){  
  49.                 scaled.destroyImages();  
  50.             }  
  51.         }  
  52.     }     
  53.    
  54.     /** 
  55.      * 水印(图片logo) 
  56.      * @param filePath  源文件路径 
  57.      * @param toImg     修改图路径 
  58.      * @param logoPath  logo图路径 
  59.      * @throws MagickException 
  60.      */  
  61.     public static void initLogoImg(String filePath, String toImg, String logoPath) throws MagickException {  
  62.         ImageInfo info = new ImageInfo();  
  63.         MagickImage fImage = null;  
  64.         MagickImage sImage = null;  
  65.         MagickImage fLogo = null;  
  66.         MagickImage sLogo = null;  
  67.         Dimension imageDim = null;  
  68.         Dimension logoDim = null;  
  69.         try {  
  70.             fImage = new MagickImage(new ImageInfo(filePath));  
  71.             imageDim = fImage.getDimension();  
  72.             int width = imageDim.width;  
  73.             int height = imageDim.height;  
  74.             if (width > 660) {  
  75.                 height = 660 * height / width;  
  76.                 width = 660;  
  77.             }  
  78.             sImage = fImage.scaleImage(width, height);     
  79.    
  80.             fLogo = new MagickImage(new ImageInfo(logoPath));  
  81.             logoDim = fLogo.getDimension();  
  82.             int lw = width / 8;  
  83.             int lh = logoDim.height * lw / logoDim.width;  
  84.             sLogo = fLogo.scaleImage(lw, lh);     
  85.    
  86.             sImage.compositeImage(CompositeOperator.AtopCompositeOp, sLogo,  width-(lw + lh/10), height-(lh + lh/10));  
  87.             sImage.setFileName(toImg);  
  88.             sImage.writeImage(info);  
  89.         } finally {  
  90.             if(sImage != null){  
  91.                 sImage.destroyImages();  
  92.             }  
  93.         }  
  94.     }     
  95.    
  96.     /** 
  97.      * 水印(文字) 
  98.         * @param filePath 源文件路径 
  99.      * @param toImg    修改图路径 
  100.      * @param text     名字(文字内容自己随意) 
  101.      * @throws MagickException 
  102.      */  
  103.     public static void initTextToImg(String filePath, String toImg,  String text) throws MagickException{  
  104.             ImageInfo info = new ImageInfo(filePath);  
  105.             if (filePath.toUpperCase().endsWith("JPG") || filePath.toUpperCase().endsWith("JPEG")) {  
  106.                 info.setCompression(CompressionType.JPEGCompression); //压缩类别为JPEG格式  
  107.                 info.setPreviewType(PreviewType.JPEGPreview); //预览格式为JPEG格式  
  108.                 info.setQuality(95);  
  109.             }  
  110.             MagickImage aImage = new MagickImage(info);  
  111.             Dimension imageDim = aImage.getDimension();  
  112.             int wideth = imageDim.width;  
  113.             int height = imageDim.height;  
  114.             if (wideth > 660) {  
  115.                 height = 660 * height / wideth;  
  116.                 wideth = 660;  
  117.             }  
  118.             int a = 0;  
  119.             int b = 0;  
  120.             String[] as = text.split("");  
  121.             for (String string : as) {  
  122.                 if(string.matches("[\u4E00-\u9FA5]")){  
  123.                     a++;  
  124.                 }  
  125.                 if(string.matches("[a-zA-Z0-9]")){  
  126.                     b++;  
  127.                 }  
  128.             }  
  129.             int tl = a*12 + b*6 + 300;  
  130.             MagickImage scaled = aImage.scaleImage(wideth, height);  
  131.             if(wideth > tl && height > 5){  
  132.                 DrawInfo aInfo = new DrawInfo(info);  
  133.                 aInfo.setFill(PixelPacket.queryColorDatabase("white"));  
  134.                 aInfo.setUnderColor(new PixelPacket(0,0,0,100));  
  135.                 aInfo.setPointsize(12);  
  136.                 //解决中文乱码问题,自己可以去随意定义个自己喜欢字体,我在这用的微软雅黑  
  137.                 String fontPath = "C:/WINDOWS/Fonts/MSYH.TTF";  
  138. //              String fontPath = "/usr/maindata/MSYH.TTF";  
  139.                 aInfo.setFont(fontPath);  
  140.                 aInfo.setTextAntialias(true);  
  141.                 aInfo.setOpacity(0);  
  142.                 aInfo.setText(" " + text + "于 " + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 上传于XXXX网,版权归作者所有!");  
  143.                 aInfo.setGeometry("+" + (wideth-tl) + "+" + (height-5));  
  144.                 scaled.annotateImage(aInfo);  
  145.             }  
  146.             scaled.setFileName(toImg);  
  147.             scaled.writeImage(info);  
  148.             scaled.destroyImages();  
  149.     }     
  150.    
  151.     /** 
  152.      * 切图 
  153.      * @param imgPath 源图路径 
  154.      * @param toPath  修改图路径 
  155.      * @param w 
  156.      * @param h 
  157.      * @param x 
  158.      * @param y 
  159.      * @throws MagickException 
  160.      */  
  161.     public static void cutImg(String imgPath, String toPath, int w, int h, int x, int y) throws MagickException {  
  162.         ImageInfo infoS = null;  
  163.         MagickImage image = null;  
  164.         MagickImage cropped = null;  
  165.         Rectangle rect = null;  
  166.         try {  
  167.             infoS = new ImageInfo(imgPath);  
  168.             image = new MagickImage(infoS);  
  169.             rect = new Rectangle(x, y, w, h);  
  170.             cropped = image.cropImage(rect);  
  171.             cropped.setFileName(toPath);  
  172.             cropped.writeImage(infoS);     
  173.    
  174.         } finally {  
  175.             if (cropped != null) {  
  176.                 cropped.destroyImages();  
  177.             }  
  178.         }  
  179.     }  
  180. }  



  • 其次自己写java代码:
[java] view plaincopy
  1. package org.uup.web;  
  2.   
  3.   
  4. import java.awt.Color;  
  5. import java.awt.Component;  
  6. import java.awt.Graphics;  
  7. import java.awt.Graphics2D;  
  8. import java.awt.Image;  
  9. import java.awt.MediaTracker;  
  10. import java.awt.Toolkit;  
  11. import java.awt.image.BufferedImage;  
  12. import java.awt.image.ConvolveOp;  
  13. import java.awt.image.Kernel;  
  14. import java.io.ByteArrayOutputStream;  
  15. import java.io.File;  
  16. import java.io.FileInputStream;  
  17. import java.io.FileOutputStream;  
  18. import java.io.IOException;  
  19. import java.io.OutputStream;  
  20.   
  21. import javax.imageio.ImageIO;  
  22. import javax.swing.ImageIcon;  
  23.   
  24. import com.sun.image.codec.jpeg.JPEGCodec;  
  25. import com.sun.image.codec.jpeg.JPEGEncodeParam;  
  26. import com.sun.image.codec.jpeg.JPEGImageEncoder;  
  27. /** 
  28.  * 图像压缩工具 
  29.  * @author lhj 
  30.  * 
  31.  */  
  32. public class ImageSizer {  
  33.   
  34.         /** 
  35.         * 压缩图片方法 
  36.         *  
  37.         * @param oldFile  将要压缩的图片 
  38.         * @param width  不能超过的最大压缩宽 
  39.         * @param height  不能超过的最大压缩长 
  40.         * @param quality  压缩清晰度 <b>建议为1.0</b> 
  41.         * @param smallIcon   压缩图片后,添加的扩展名 
  42.         * @return 
  43.          * @throws IOException  
  44.         */  
  45.     public static void imageZip(File oldFile, File destFile, String format, int maxWidth, int maxHeight, float quality) throws IOException {  
  46.         FileOutputStream out = null;  
  47.         try {  
  48.             // 文件不存在时  
  49.             if (!oldFile.exists())  
  50.                 return;  
  51.             /** 对服务器上的临时文件进行处理 */  
  52.             Image srcFile = ImageIO.read(oldFile);  
  53.             int new_w = 0, new_h = 0;  
  54.             // 获取图片的实际大小 高度  
  55.             int h = (int) srcFile.getHeight(null);  
  56.             // 获取图片的实际大小 宽度  
  57.             int w = (int) srcFile.getWidth(null);  
  58.             // 为等比缩放计算输出的图片宽度及高度  
  59.             if ((((double) w) > (double) maxWidth) || (((double) h) > (double) maxHeight)) {  
  60.                 // 为等比缩放计算输出的图片宽度及高度  
  61.                 double rateW = ((double) srcFile.getWidth(null)) / (double) maxWidth * 1.0;  
  62.                 double rateH = ((double) srcFile.getHeight(null)) / (double) maxHeight * 1.0;  
  63.                 // 根据缩放比率大的进行缩放控制  
  64.                 //double rate = rateW > rateH ? rateW : rateH;  
  65.                 double rate;  
  66.                 char zipType;  
  67.                 if(rateW > rateH){  
  68.                     rate = rateW;  
  69.                     zipType = 'W';  
  70.                 } else {  
  71.                     rate = rateH;  
  72.                     zipType = 'H';  
  73.                 }  
  74.                 new_w = (int) (((double) srcFile.getWidth(null)) / rate);  
  75.                 new_h = (int) (((double) srcFile.getHeight(null)) / rate);  
  76.                   
  77.                 double rate2 = 0;  
  78.                 if(zipType == 'W' && new_h > maxHeight){  
  79.                     rate = (double) new_h / (double) maxHeight * 1.0;  
  80.                 } else if(zipType == 'H' && new_w > maxWidth){  
  81.                     rate = (double) new_w / (double) maxWidth * 1.0;  
  82.                 }  
  83.                 if(rate2 != 0){  
  84.                     new_w = (int) (((double) new_w) / rate);  
  85.                     new_h = (int) (((double) new_h) / rate);  
  86.                     System.out.println("2次修改宽高。");  
  87.                 }  
  88.             } else {  
  89.                 new_w = w;  
  90.                 new_h = h;  
  91.             }  
  92.               
  93.               if ( new_w < 1 )   
  94.                   throw new IllegalArgumentException( "image width " + new_w + " is out of range" );  
  95.                if ( new_h < 1 )   
  96.                   throw new IllegalArgumentException( "image height " + new_h + " is out of range" );  
  97.   
  98.             /** 宽,高设定 */  
  99.             BufferedImage tag = new BufferedImage(new_w, new_h,  
  100.                     BufferedImage.TYPE_INT_RGB);  
  101.             tag.getGraphics().drawImage(srcFile, 00, new_w, new_h, null);  
  102.               
  103.             out = new FileOutputStream(destFile);  
  104.             JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);  
  105.             JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);  
  106.             /** 压缩质量 */  
  107.             jep.setQuality(quality, true);  
  108.             encoder.encode(tag, jep);  
  109.             out.close();  
  110.             srcFile.flush();  
  111.         } finally{  
  112.             if(out != null)out.close();  
  113.         }  
  114.     }  
  115.   
  116.       
  117.       public static final MediaTracker tracker = new MediaTracker(new Component() {  
  118.             private static final long serialVersionUID = 1234162663955668507L;}   
  119.         );  
  120.         
  121.           
  122.         /**方法二  
[java] view plaincopy
  1.          * @param originalFile 原图像  
  2.          * @param resizedFile 压缩后的图像  
  3.          * @param width 图像宽  
  4.          * @param format 图片格式 jpg, png, gif(非动画)  
  5.          * @throws IOException  
  6.          */  
  7.         public static void resize(File originalFile, File resizedFile, int width, String format) throws IOException {  
  8.             FileInputStream fis = null;  
  9.             ByteArrayOutputStream byteStream = null;  
  10.             try{  
  11.                 if(format!=null && "gif".equals(format.toLowerCase())){  
  12.                     resize(originalFile, resizedFile, width, 1);  
  13.                     return;  
  14.                 }  
  15.                 fis = new FileInputStream(originalFile);  
  16.                 byteStream = new ByteArrayOutputStream();  
  17.                 int readLength = -1;  
  18.                 int bufferSize = 1024;  
  19.                 byte bytes[] = new byte[bufferSize];  
  20.                 while ((readLength = fis.read(bytes, 0, bufferSize)) != -1) {  
  21.                     byteStream.write(bytes, 0, readLength);  
  22.                 }  
  23.                 byte[] in = byteStream.toByteArray();  
  24.                 fis.close();  
  25.                 byteStream.close();  
  26.               
  27.                 Image inputImage = Toolkit.getDefaultToolkit().createImage( in );  
  28.                 waitForImage( inputImage );  
  29.                 int imageWidth = inputImage.getWidth( null );  
  30.                 if ( imageWidth < 1 )   
  31.                    throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );  
  32.                 int imageHeight = inputImage.getHeight( null );  
  33.                 if ( imageHeight < 1 )   
  34.                    throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );  
  35.                   
  36.                 // Create output image.  
  37.                 int height = -1;  
  38.                 double scaleW = (double) imageWidth / (double) width;  
  39.                 double scaleY = (double) imageHeight / (double) height;  
  40.                 if (scaleW >= 0 && scaleY >=0) {  
  41.                     if (scaleW > scaleY) {  
  42.                         height = -1;  
  43.                     } else {  
  44.                         width = -1;  
  45.                     }  
  46.                 }  
  47.                 Image outputImage = inputImage.getScaledInstance( width, height, java.awt.Image.SCALE_DEFAULT);  
  48.                 checkImage( outputImage );          
  49.                 encode(new FileOutputStream(resizedFile), outputImage, format);      
  50.             }finally{  
  51.                 try {  
  52.                     if(byteStream != null) {  
  53.                         byteStream.close();  
  54.                     }  
  55.                     if(fis != null) {  
  56.                         fis.close();  
  57.                     }  
  58.                 } catch (IOException e) {  
  59.                     e.printStackTrace();  
  60.                 }  
  61.             }  
  62.         }      
  63.   
  64.         /** Checks the given image for valid width and height. */  
  65.         private static void checkImage( Image image ) {  
  66.            waitForImage( image );  
  67.            int imageWidth = image.getWidth( null );  
  68.            if ( imageWidth < 1 )   
  69.               throw new IllegalArgumentException( "image width " + imageWidth + " is out of range" );  
  70.            int imageHeight = image.getHeight( null );  
  71.            if ( imageHeight < 1 )   
  72.               throw new IllegalArgumentException( "image height " + imageHeight + " is out of range" );  
  73.         }  
  74.   
  75.         /** Waits for given image to load. Use before querying image height/width/colors. */  
  76.         private static void waitForImage( Image image ) {  
  77.            try {  
  78.               tracker.addImage( image, 0 );  
  79.               tracker.waitForID( 0 );  
  80.               tracker.removeImage(image, 0);  
  81.            } catch( InterruptedException e ) { e.printStackTrace(); }  
  82.         }   
  83.   
  84.         /** Encodes the given image at the given quality to the output stream. */  
  85.         private static void encode( OutputStream outputStream, Image outputImage, String format )   
  86.            throws java.io.IOException {  
  87.             try {  
  88.                int outputWidth  = outputImage.getWidth( null );  
  89.                if ( outputWidth < 1 )   
  90.                   throw new IllegalArgumentException( "output image width " + outputWidth + " is out of range" );  
  91.                int outputHeight = outputImage.getHeight( null );  
  92.                if ( outputHeight < 1 )   
  93.                   throw new IllegalArgumentException( "output image height " + outputHeight + " is out of range" );  
  94.       
  95.                // Get a buffered image from the image.  
  96.                BufferedImage bi = new BufferedImage( outputWidth, outputHeight,  
  97.                   BufferedImage.TYPE_INT_RGB );                                                     
  98.                Graphics2D biContext = bi.createGraphics();  
  99.                biContext.drawImage( outputImage, 00null );  
  100.                ImageIO.write(bi, format, outputStream);  
  101.                outputStream.flush();      
  102.             }finally{  
  103.                 if(outputStream != null) {  
  104.                     outputStream.close();  
  105.                 }  
  106.             }  
  107.         }   
  108.           
  109.         /** 
  110.          * 缩放gif图片 
  111.          * @param originalFile 原图片 
  112.          * @param resizedFile 缩放后的图片 
  113.          * @param newWidth 宽度 
  114.          * @param quality 缩放比例 (等比例) 
  115.          * @throws IOException 
  116.          */  
  117.         private static void resize(File originalFile, File resizedFile, int newWidth, float quality) throws IOException {  
  118.             if (quality < 0 || quality > 1) {  
  119.                 throw new IllegalArgumentException("Quality has to be between 0 and 1");  
  120.             }   
  121.             ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());  
  122.             Image i = ii.getImage();  
  123.             Image resizedImage = null;   
  124.             int iWidth = i.getWidth(null);  
  125.             int iHeight = i.getHeight(null);   
  126.             if (iWidth > iHeight) {  
  127.                 resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight) / iWidth, Image.SCALE_SMOOTH);  
  128.             } else {  
  129.                 resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight, newWidth, Image.SCALE_SMOOTH);  
  130.             }   
  131.             // This code ensures that all the pixels in the image are loaded.  
  132.             Image temp = new ImageIcon(resizedImage).getImage();   
  133.             // Create the buffered image.  
  134.             BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null), temp.getHeight(null),  
  135.                                                             BufferedImage.TYPE_INT_RGB);   
  136.             // Copy image to buffered image.  
  137.             Graphics g = bufferedImage.createGraphics();   
  138.             // Clear background and paint the image.  
  139.             g.setColor(Color.white);  
  140.             g.fillRect(00, temp.getWidth(null), temp.getHeight(null));  
  141.             g.drawImage(temp, 00null);  
  142.             g.dispose();   
  143.             // Soften.  
  144.             float softenFactor = 0.05f;  
  145.             float[] softenArray = {0, softenFactor, 0, softenFactor, 1-(softenFactor*4), softenFactor, 0, softenFactor, 0};  
  146.             Kernel kernel = new Kernel(33, softenArray);  
  147.             ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);  
  148.             bufferedImage = cOp.filter(bufferedImage, null);   
  149.             // Write the jpeg to a file.  
  150.             FileOutputStream out = new FileOutputStream(resizedFile);          
  151.             // Encodes image as a JPEG data stream  
  152.             JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);   
  153.             JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);   
  154.             param.setQuality(quality, true);   
  155.             encoder.setJPEGEncodeParam(param);  
  156.             encoder.encode(bufferedImage);  
  157.         }  
  158.           
  159.     
  160.         /** 
  161.          * 图片缩放(图片等比例缩放为指定大小,空白部分以白色填充) 
  162.          *  
  163.          * @param srcBufferedImage  源图片 
  164.          * @param destFile缩放后的图片文件 
  165.          * @param destHeight 
  166.          * @param destWidth 
  167.          */  
  168.         public static void zoom(BufferedImage srcBufferedImage, File destFile, String format, int destHeight, int destWidth) {  
  169.             try {  
  170.                 int imgWidth = destWidth;  
  171.                 int imgHeight = destHeight;  
  172.                 int srcWidth = srcBufferedImage.getWidth();  
  173.                 int srcHeight = srcBufferedImage.getHeight();  
  174.                 double scaleW = destWidth * 1.0 / srcWidth;  
  175.                 double scaleH = destHeight * 1.0 / srcHeight;  
  176.                 if (scaleW >= scaleH) {  
  177.                     double imgWidth1 = scaleH * srcWidth;  
  178.                     double imgHeight1 = scaleH * srcHeight;   
  179.                     imgWidth = (int)imgWidth1;  
  180.                     imgHeight = (int)imgHeight1;  
  181.                 } else {  
  182.                     double imgWidth1 = scaleW * srcWidth;  
  183.                     double imgHeight1 = scaleW * srcHeight;   
  184.                     imgWidth = (int)imgWidth1;  
  185.                     imgHeight = (int)imgHeight1;  
  186.                 }  
  187.                 BufferedImage destBufferedImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);  
  188.                 Graphics2D graphics2D = destBufferedImage.createGraphics();  
  189.                 graphics2D.setBackground(Color.WHITE);   
  190.                 graphics2D.clearRect(00, destWidth, destHeight);  
  191.                 graphics2D.drawImage(srcBufferedImage.getScaledInstance(imgWidth, imgHeight, Image.SCALE_SMOOTH), (destWidth / 2) - (imgWidth / 2), (destHeight / 2) - (imgHeight / 2), null);  
  192.                 graphics2D.dispose();  
  193.                 ImageIO.write(destBufferedImage, format, destFile);  
  194.             } catch (IOException e) {  
  195.                 e.printStackTrace();  
  196.             }  
  197.         }  

0 0
原创粉丝点击