java按比例之原图生成缩略图
2019獨角獸企業重金招聘Python工程師標準>>>
package com.wxp.test;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import javax.imageio.ImageIO;
import sun.awt.image.PNGImageDecoder;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.imageio.plugins.png.PNGImageWriter;
public class CreateShortImage {
?? ?public final static ?String DDIST="D:\\WXPworkspace\\shortImage\\";
?? ?public final static ?String DSRC="D:\\WXPworkspace\\";
?? ?
?? ?/**
?? ? * 創建圖片縮略圖(等比縮放)
?? ? * @param src
?? ? * @param dist
?? ? * @param width
?? ? * @param height
?? ? */
?? ?public static void createThumbnail(String src,String dist,float width,float height){
?? ??? ?try {
?? ??? ??? ?File srcFile = new File(src);
?? ??? ??? ?if(!srcFile.exists()){
?? ??? ??? ??? ?System.out.println("文件不存在");
?? ??? ??? ??? ?return;
?? ??? ??? ?}
?? ??? ??? ?BufferedImage image = ImageIO.read(srcFile);
?? ??? ??? ?//獲得縮放比例
?? ??? ??? ?double ratio = 1.0;
?? ??? ??? ?//判斷如果高、寬都不大于設定值,則不處理
?? ??? ??? ?if(image.getHeight() > height || image.getWidth() > width){
?? ??? ??? ??? ?if( image.getHeight() > image.getWidth()){
?? ??? ??? ??? ??? ?ratio = height / image.getHeight();
?? ??? ??? ??? ?}else{
?? ??? ??? ??? ??? ?ratio = width / image.getWidth();
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ??? ?//計算新的圖面寬度和高度
?? ??? ??? ?int newWidth = (int)(image.getWidth() * ratio);
?? ??? ??? ?int newHeight = (int)(image.getHeight() * ratio);
?? ??? ??? ?BufferedImage bfiImage = new BufferedImage(newWidth, newHeight,BufferedImage.TYPE_INT_BGR);
?? ??? ??? ?bfiImage.getGraphics().drawImage(
?? ??? ??? ??? ??? ?image.getScaledInstance(newWidth, newHeight,Image.SCALE_SMOOTH),0,0,null);
?? ??? ??? ?FileOutputStream os = new FileOutputStream(dist);
?? ??? ??? ?JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(os);
?? ??? ??? ?encoder.encode(bfiImage);
?? ??? ??? ?os.close();
?? ??? ??? ?System.out.println("創建縮略圖成功");
?? ??? ?} catch (Exception e) {
?? ??? ??? ?// TODO: handle exception
?? ??? ??? ?System.out.println("創建縮略圖發生異常"+e.getMessage());
?? ??? ?}
?? ?}
?? ?/**
?? ? * @param argsshortImage
?? ? */
?? ?public static void main(String[] args) {
?? ??? ?// TODO Auto-generated method stub
?? ??? ? ?createThumbnail(DSRC+"1.png", DDIST+"a.png", 100, 100);
?? ? ? ? ?createThumbnail(DSRC+"2.png", DDIST+"b.png", 100, 100);
?? ? ? ? ?createThumbnail(DSRC+"3.jpg", DDIST+"c.jpg", 100, 100);
?? ?}
}
?
轉載于:https://my.oschina.net/u/3378039/blog/1860208
總結
以上是生活随笔為你收集整理的java按比例之原图生成缩略图的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: django中的Ajax文件上传
- 下一篇: 笔记:后端 - Redis