標籤:圖片 java縮圖 壓縮 java
import com.sun.image.codec.jpeg.JPEGImageEncoder;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGEncodeParam;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.util.HashMap;import java.util.List;import java.util.ArrayList;import java.io.File;import java.io.IOException;import java.io.FileOutputStream;import java.util.Map;public class ResizeImage { /** * @param im 原始映像 * @param resizeTimes 需要縮小的倍數,縮小2倍為原來的1/2 ,這個數值越大,返回的圖片越小 * @return 返回處理後的映像 */ public BufferedImage resizeImage(BufferedImage im, float resizeTimes) { /*原始映像的寬度和高度*/ int width = im.getWidth(); int height = im.getHeight(); /*調整後的圖片的寬度和高度*/ int toWidth = (int) (Float.parseFloat(String.valueOf(width)) / resizeTimes); int toHeight = (int) (Float.parseFloat(String.valueOf(height)) / resizeTimes); /*新產生結果圖片*/ BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB); result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null); return result; } /** * @param im 原始映像 * @param resizeTimes 倍數,比如0.5就是縮小一半,0.98等等double類型 * @return 返回處理後的映像 */ public BufferedImage zoomImage(BufferedImage im, float resizeTimes) { /*原始映像的寬度和高度*/ int width = im.getWidth(); int height = im.getHeight(); /*調整後的圖片的寬度和高度*/ int toWidth = (int) (Float.parseFloat(String.valueOf(width)) * resizeTimes); int toHeight = (int) (Float.parseFloat(String.valueOf(height)) * resizeTimes); /*新產生結果圖片*/ BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB); result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null); return result; } /** * @param path 要轉化的映像的檔案夾,就是存放映像的檔案夾路徑 * @param type 圖片的尾碼名組成的數組 * @return */ public List<BufferedImage> getImageList(String path, String[] type) throws IOException{ Map<String,Boolean> map = new HashMap<String, Boolean>(); for(String s : type) { map.put(s,true); } List<BufferedImage> result = new ArrayList<BufferedImage>(); File[] fileList = new File(path).listFiles(); for (File f : fileList) { if(f.length() == 0) continue; if(map.get(getExtension(f.getName())) == null) continue; result.add(javax.imageio.ImageIO.read(f)); } return result; } /** * 把圖片寫到磁碟上 * @param im * @param path eg: C://home// 圖片寫入的檔案夾地址 * @param fileName DCM1987.jpg 寫入圖片的名字 * @return */ public boolean writeToDisk(BufferedImage im, String path, String fileName) { File f = new File(path + fileName); String fileType = getExtension(fileName); if (fileType == null) return false; try { ImageIO.write(im, fileType, f); im.flush(); return true; } catch (IOException e) { return false; } } public boolean writeHighQuality(BufferedImage im, String fileFullPath) { try { /*輸出到檔案流*/ FileOutputStream newimage = new FileOutputStream(fileFullPath+System.currentTimeMillis()+".jpg"); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage); JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(im); /* 壓縮品質 */ jep.setQuality(1f, true); encoder.encode(im, jep); /*近JPEG編碼*/ newimage.close(); return true; } catch (Exception e) { return false; } } /** * 返迴文件的檔案尾碼名 * @param fileName * @return */ public String getExtension(String fileName) { try { return fileName.split("\\.")[fileName.split("\\.").length - 1]; } catch (Exception e) { return null; } } public static void main(String[] args) throws Exception{ String inputFoler = "c:\\cameraImage" ; /*這兒填寫你存放要縮小圖片的檔案夾全地址*/ String outputFolder = "c:\\output\\"; /*這兒填寫你轉化後的圖片存放的檔案夾*/ float times = 0.5f; /*這個參數是要轉化成的倍數,如果是1就是轉化成1倍*/ ResizeImage r = new ResizeImage(); List<BufferedImage> imageList = r.getImageList(inputFoler,new String[] {"jpg"}); for(BufferedImage i : imageList) { r.writeHighQuality(r.zoomImage(i,times),outputFolder); } }}
如果不能匯入jar包就用下面解決方案:
報錯:
Access restriction:The type JPEGCodec is not accessible due to restriction on required library C:\Program Files\Java\jre6\lib\rt.jar
解決方案:
Project -> Properties -> libraries,
先remove掉JRE System Library,然後再Add Library重新加入。
============================================
在Eclipse中處理圖片,需要引入兩個包:
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
報錯:
Access restriction: The type JPEGImageEncoder is not accessible due to restriction on required library C:\Java\jre1.6.0_07\lib\rt.jar
此時解決辦法:
Eclipse 預設把這些受訪問限制的API設成了ERROR。只要把Windows-Preferences-Java-Complicer- Errors/Warnings裡面的Deprecated and restricted API中的Forbidden references(access rules)選為Warning就可以編譯通過。
優先選擇第一種方法
自己在整合在項目中的使用案例:
package webservice.util;import javax.imageio.ImageIO;import com.sun.image.codec.jpeg.JPEGCodec;import com.sun.image.codec.jpeg.JPEGEncodeParam;import com.sun.image.codec.jpeg.JPEGImageEncoder;import java.awt.image.BufferedImage;import java.util.HashMap;import java.util.List;import java.util.ArrayList;import java.io.File;import java.io.IOException;import java.io.FileOutputStream;import java.util.Map;public class ResizeImage { /** * @param im 原始映像 * @param resizeTimes 需要縮小的倍數,縮小2倍為原來的1/2 ,這個數值越大,返回的圖片越小 * @return 返回處理後的映像 */ public BufferedImage resizeImage(BufferedImage im, float resizeTimes) { /*原始映像的寬度和高度*/ int width = im.getWidth(); int height = im.getHeight(); /*調整後的圖片的寬度和高度*/ int toWidth = (int) (Float.parseFloat(String.valueOf(width)) / resizeTimes); int toHeight = (int) (Float.parseFloat(String.valueOf(height)) / resizeTimes); /*新產生結果圖片*/ BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB); result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null); return result; } /** * @param im 原始映像 * @param resizeTimes 倍數,比如0.5就是縮小一半,0.98等等double類型 * @return 返回處理後的映像 */ public BufferedImage zoomImage(BufferedImage im) { /*原始映像的寬度和高度*/ /*調整後的圖片的寬度和高度*/ int toWidth=64; int toHeight=64; /*新產生結果圖片*/ BufferedImage result = new BufferedImage(toWidth, toHeight, BufferedImage.TYPE_INT_RGB); result.getGraphics().drawImage(im.getScaledInstance(toWidth, toHeight, java.awt.Image.SCALE_SMOOTH), 0, 0, null); return result; } /** * @param path 要轉化的映像的檔案夾,就是存放映像的檔案夾路徑 * @param type 圖片的尾碼名組成的數組 * @return */ public List<BufferedImage> getImageList(String path, String[] type) throws IOException{ Map<String,Boolean> map = new HashMap<String, Boolean>(); for(String s : type) { map.put(s,true); } List<BufferedImage> result = new ArrayList<BufferedImage>(); File[] fileList = new File(path).listFiles(); for (File f : fileList) { if(f.length() == 0) continue; if(map.get(getExtension(f.getName())) == null) continue; result.add(javax.imageio.ImageIO.read(f)); } return result; } public BufferedImage getImage(String path) throws IOException{ return javax.imageio.ImageIO.read(new File(path)); } /** * 把圖片寫到磁碟上 * @param im * @param path eg: C://home// 圖片寫入的檔案夾地址 * @param fileName DCM1987.jpg 寫入圖片的名字 * @return */ public boolean writeToDisk(BufferedImage im, String path, String fileName) { File f = new File(path + fileName); String fileType = getExtension(fileName); if (fileType == null) return false; try { ImageIO.write(im, fileType, f); im.flush(); return true; } catch (IOException e) { return false; } } public boolean writeHighQuality(BufferedImage im, String fileFullPath) { try { /*輸出到檔案流*/ FileOutputStream newimage = new FileOutputStream(fileFullPath); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage); JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(im); /* 壓縮品質 */ jep.setQuality(1f, true); encoder.encode(im, jep); /*近JPEG編碼*/ newimage.close(); return true; } catch (Exception e) { return false; } } /** * 返迴文件的檔案尾碼名 * @param fileName * @return */ public String getExtension(String fileName) { try { return fileName.split("\\.")[fileName.split("\\.").length - 1]; } catch (Exception e) { return null; } }//測試 public static void main(String[] args) throws Exception{ /*System.out.println(123); String inputFoler = "F:\\testimages\\yuan"; 這兒填寫你存放要縮小圖片的檔案夾全地址 String outputFolder = "F:\\testimages\\ys"; 這兒填寫你轉化後的圖片存放的檔案夾 float times = 0.5f; 這個參數是要轉化成的倍數,如果是1就是轉化成1倍 ResizeImage r = new ResizeImage(); List<BufferedImage> imageList = r.getImageList(inputFoler,new String[] {"png"}); for(BufferedImage i : imageList) { r.writeHighQuality(r.zoomImage(i,times),outputFolder); System.out.println("..."); }*/ ResizeImage r=new ResizeImage(); String filepath="E:\\file\\"; String filename="1.jpg"; BufferedImage im=r.getImage(filepath+filename); r.writeHighQuality(r.zoomImage(im), filepath+"s_"+filename);//為防止覆蓋原圖片,加s_區分是壓縮以後的圖片 }}
Java 實現產生圖片縮圖,縮小高清圖片