為圖片檔案產生縮圖

來源:互聯網
上載者:User
package ImageTest;import java.awt.Graphics2D;import java.awt.RenderingHints;import java.awt.geom.AffineTransform;import java.awt.image.BufferedImage;import java.awt.image.ColorModel;import java.awt.image.WritableRaster;import java.io.File;import java.io.IOException;import javax.imageio.ImageIO;public class Test {/** * 為圖片檔案產生縮圖 * @param args */public static void main(String[] args) {try {//參數1(源圖片路徑),參數2 (縮圖路徑),參數3(縮圖寬)參數4(縮圖高)Test.saveImageAsJpg("E:\\QQ20120612154244.gif", "E:\\test.jpg", 400, 400);} catch (IOException e) {e.printStackTrace();}}/** * 產生縮圖 * @param fromFileStr 源圖片路徑 * @param saveToFileStr 縮圖路徑 * @param width 縮圖的寬 * @param hight 縮圖的高 * @throws IOException */public static void saveImageAsJpg(String fromFileStr,String saveToFileStr,int width,int hight) throws IOException{BufferedImage srcImage;String imgType="JPEG";if(fromFileStr.toLowerCase().endsWith(".png")){imgType="PNG";}File saveFile=new File(saveToFileStr);File fromFile=new File(fromFileStr);srcImage=ImageIO.read(fromFile);if(width>0||hight>0){srcImage=resize(srcImage,width,hight);}ImageIO.write(srcImage, imgType, saveFile);}/** * 將源圖片的BufferedImage對象產生縮圖 * @param source 源圖片的BufferedImage對象 * @param targetW 縮圖的寬 * @param targetH 縮圖的高 * @return */private static BufferedImage resize(BufferedImage source, int targetW,int targetH) {int type=source.getType();BufferedImage target=null;double sx=(double)targetW/source.getWidth();double sy=(double)targetH/source.getHeight();if(sx>sy){sx=sy;targetW=(int)(sx*source.getWidth());}else{sy=sx;targetH=(int)(sy*source.getHeight());}if(type==BufferedImage.TYPE_CUSTOM){ColorModel cm=source.getColorModel();WritableRaster raster=cm.createCompatibleWritableRaster(targetW, targetH);boolean alphaPremultiplied=cm.isAlphaPremultiplied();target=new BufferedImage(cm,raster,alphaPremultiplied,null);}else{target=new BufferedImage(targetW, targetH,type);}Graphics2D g=target.createGraphics();g.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));g.dispose();return target;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.