java實(shí)現(xiàn)上傳圖片尺寸修改和質(zhì)量壓縮
本文實(shí)例為大家分享了java實(shí)現(xiàn)上傳圖片尺寸修改和質(zhì)量壓縮的具體代碼,供大家參考,具體內(nèi)容如下
package com.zity.frame.util; ? /** ? ?* ?縮略圖實(shí)現(xiàn),將圖片(jpg、bmp、png、gif等等)真實(shí)的變成想要的大小 ? ?*/ ? import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; import net.sourceforge.pinyin4j.PinyinHelper; ? import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.Random; ?? /******************************************************************************* ? ?* 縮略圖類(通用) 本java類能將jpg、bmp、png、gif圖片文件,進(jìn)行等比或非等比的大小轉(zhuǎn)換。 具體使用方法 ? ?* compressPic(大圖片路徑,生成小圖片路徑,大圖片文件名,生成小圖片文名,生成小圖片寬度,生成小圖片高度,是否等比縮放(默認(rèn)為true)) ? ?*/ ? ?public class CompressPic { ? ? ?private File file = null; // 文件對象 ? ? ?private String inputDir; // 輸入圖路徑 ? ? ?private String outputDir; // 輸出圖路徑 ? ? ?private String inputFileName; // 輸入圖文件名 ? ? ?private String outputFileName; // 輸出圖文件名 ? ? ?private int outputWidth = 300; // 默認(rèn)輸出圖片寬 ? ? ?private int outputHeight = 150; // 默認(rèn)輸出圖片高 ? ? ?private boolean proportion = true; // 是否等比縮放標(biāo)記(默認(rèn)為等比縮放) ? ? ?public CompressPic() { // 初始化變量 ? ? ? ? ?inputDir = ""; ? ? ? ? ? ? ?outputDir = ""; ? ? ? ? ? ? ?inputFileName = ""; ? ? ? ? ? ? ?outputFileName = ""; ? ? ? ? ? ? ?outputWidth = 300; ? ? ? ? ? ? ?outputHeight = 150; ? ? ? ? ?} ? ? ? ? ?public void setInputDir(String inputDir) { ? ? ? ? ? ? ?this.inputDir = inputDir; ? ? ? ? ?} ? ? ? ? ?public void setOutputDir(String outputDir) { ? ? ? ? ? ? ?this.outputDir = outputDir; ? ? ? ? ?} ? ? ? ? ?public void setInputFileName(String inputFileName) { ? ? ? ? ? ? ?this.inputFileName = inputFileName; ?? ? ? ?} ? ? ? ? ?public void setOutputFileName(String outputFileName) { ? ? ? ? ? ? ?this.outputFileName = outputFileName; ? ? ? ? ?} ? ? ? ? ?public void setOutputWidth(int outputWidth) { ?? ? ? ? ? ?this.outputWidth = outputWidth; ? ? ? ? ?} ? ? ? ? ?public void setOutputHeight(int outputHeight) { ? ? ? ? ? ? ?this.outputHeight = outputHeight; ? ? ? ? ?} ? ? ? ? ?public void setWidthAndHeight(int width, int height) { ? ? ? ? ? ? ?this.outputWidth = width; ?? ? ? ? ? ?this.outputHeight = height; ? ? ? ? ?} ? ? ? ? ? ?? ? ? ?/* ?? ? ? ? * 獲得圖片大小 ?? ? ? ? * 傳入?yún)?shù) String path :圖片路徑 ?? ? ? ? */ ? ? ? ? ?public long getPicSize(String path) { ? ? ? ? ? ? ?file = new File(path); ? ? ? ? ?return file.length(); ? ? ?} ?? ? ? ? ?? ? ? ?/** ? ? ? * 圖片處理 ? ? ? * @return ? ? ? */ ? ? ?public String compressPic() { ? ? ? ? ? ? ?try { ? ? ? ? ? ? ? ? ?//獲得源文件 ? ? ? ? ? ? ? ? ?file = new File(inputDir + inputFileName); ? ? ? ? ? ? ? ? ?if (!file.exists()) { ? ? ? ? ? ? ? ? ? ? ?return ""; ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ?// 生成存儲路徑 ? ? ? ? ? ? ?File outDir = new File(outputDir); ? ? ? ? ? ? ?if(!outDir.exists()){ ? ? ? ? ? ? ?? ? outDir.mkdirs(); ? ? ? ? ? ? ?} ? ? ? ? ? ? ?Image img = ImageIO.read(file); ? ? ? ? ? ? ?// 判斷圖片格式是否正確 ? ? ? ? ? ? ? ? ?if(img==null){ ? ? ? ? ? ? ?? ? return ""; ? ? ? ? ? ? ?} ? ? ? ? ? ? ?if (img.getWidth(null) == -1) { ?? ? ? ? ? ? ? ? ? ?System.out.println(" can't read,retry!" + "<BR>"); ? ? ? ? ? ? ? ? ? ? ?return "no"; ? ? ? ? ? ? ? ? ?} else { ? ? ? ? ? ? ? ? ? ? ?int newWidth; int newHeight; ? ? ? ? ? ? ? ? ? ? ?// 判斷是否是等比縮放 ? ? ? ? ? ? ? ? ? ? ?if (this.proportion == true) { ? ? ? ? ? ? ? ? ? ? ? ? ?// 為等比縮放計算輸出的圖片寬度及高度 ? ? ? ? ? ? ? ? ? ? ?? ? int w =img.getWidth(null); ? ? ? ? ? ? ? ? ?? ? int h = img.getHeight(null); ? ? ? ? ? ? ? ? ?? ? //如果圖片的寬度小于等于250,并且高度小于等于183,圖片原樣輸出 ? ? ? ? ? ? ? ? ?? ? if(w<=300){ ? ? ? ? ? ? ? ? ?? ??? ? outputWidth=w; ? ? ? ? ? ? ? ? ?? ? } ? ? ? ? ? ? ? ? ?? ? if(h<=150){ ? ? ? ? ? ? ? ? ?? ??? ? outputHeight=h; ? ? ? ? ? ? ? ? ?? ? } ? ? ? ? ? ? ? ? ? ? ?double rate1 = ((double) img.getWidth(null)) / (double) outputWidth; ? ? ? ? ? ? ? ? ? ? ? ? ?double rate2 = ((double) img.getHeight(null)) / (double) outputHeight; ? ? ? ? ? ? ? ? ? ? ? ? ?// 根據(jù)縮放比率大的進(jìn)行縮放控制 ? ? // ? ? ? ? ? ? ? ? ? ? double rate = rate1 > rate2 ? rate1 : rate2; ? ? ? ? ? ? ? ? ? ? ?// 保證寬度為250px ? ? ? ? ? ? ? ? ? ? ?double rate = rate1; ? ? ? ? ? ? ? ? ? ? ?newWidth = (int) (((double) img.getWidth(null)) / rate); ? ? ? ? ? ? ? ? ? ? ? ? ?newHeight = (int) (((double) img.getHeight(null)) / rate2); ? ? ? ? ? ? ? ? ? ? ?} else { ? ? ? ? ? ? ? ? ? ? ? ? ?newWidth = outputWidth; // 輸出的圖片寬度 ? ? ? ? ? ? ? ? ? ? ? ? ?newHeight = outputHeight; // 輸出的圖片高度 ? ? ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//重新設(shè)置高寬為圖片真實(shí)高寬,上面的高寬是其他項(xiàng)目需要300*150的,我沒得空刪掉 ?? ??? ??? ??? ? newWidth = getImgWidth(file); ?? ??? ??? ??? ? newHeight = getImgHeight(file); ? ? ? ? ? ? ? ? BufferedImage tag = new BufferedImage((int) newWidth, (int) newHeight, BufferedImage.TYPE_INT_RGB); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? /* ? ? ? ? ? ? ? ? ? ?* Image.SCALE_SMOOTH 的縮略算法 生成縮略圖片的平滑度的 ? ? ? ? ? ? ? ? ? ?* 優(yōu)先級比速度高 生成的圖片質(zhì)量比較好 但速度慢 ? ? ? ? ? ? ? ? ? ?*/ ? ? ? ? ? ? ? ? ? ? tag.getGraphics().drawImage(img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH), 0, 0, null); ?? ? ? ? ? ? ? ? ? FileOutputStream out = new FileOutputStream(outputDir + outputFileName); ?? ? ? ? ? ? ? ? ? // JPEGImageEncoder可適用于其他圖片類型的轉(zhuǎn)換 ? ? ? ? ? ? ? ? ? ? JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); ? ? ? ? ? ? ? ? ? ? encoder.encode(tag); ? ? ? ? ? ? ? ? ? ? out.close(); ? ? ? ? ? ? ? ? ?} ? ? ? ? ? ? ?} catch (IOException ex) { ? ? ? ? ? ? ? ? ?ex.printStackTrace(); ? ? ? ? ? ? ?} ? ? ? ? ? ? ?return "ok"; ? ? ? ? } ? ?? ? ? /** ? ? ?* 圖片處理入口 ? ? ?* @param inputDir 輸入圖路徑 ? ? ?* @param outputDir 輸出圖路徑 ? ? ?* @param inputFileName 輸入圖名 ? ? ?* @param outputFileName 輸出圖名 ? ? ?* @return ? ? ?*/ ? ? public String compressPic (String inputDir, String outputDir, String inputFileName, String outputFileName) { ? ? ? ? ? ? // 輸入圖路徑 ? ? ? ? ? ? this.inputDir = inputDir; ? ? ? ? ? ? // 輸出圖路徑 ? ? ? ? ? ? this.outputDir = outputDir; ? ? ? ? ? ? // 輸入圖文件名 ? ? ? ? ? ? this.inputFileName = inputFileName; ? ? ? ? ? ? // 輸出圖文件名 ?? ? ? ? ? this.outputFileName = outputFileName; ? ? ? ? ? ? return compressPic(); ? ? ? ? } ? ? ? ?? ? ? /** ? ? ?* 圖片處理入口 ? ? ?* @param inputDir 輸入圖路徑 ? ? ?* @param outputDir 輸出圖路徑 ? ? ?* @param inputFileName 輸入圖名 ? ? ?* @param outputFileName 輸出圖名 ? ? ?* @param width 輸出圖寬度 ? ? ?* @param height 輸入圖寬度 ? ? ?* @param gp 等比縮放 ? ? ?* @return ? ? ?*/ ? ? public String compressPic(String inputDir, String outputDir, String inputFileName, String outputFileName, int width, int height, boolean gp) { ? ? ? ? ? ? // 輸入圖路徑 ? ? ? ? ? ? this.inputDir = inputDir; ? ? ? ? ? ? // 輸出圖路徑 ? ? ? ? ? ? this.outputDir = outputDir; ? ? ? ? ? ? // 輸入圖文件名 ? ? ? ? ? ? this.inputFileName = inputFileName; ? ? ? ? ? ? // 輸出圖文件名 ? ? ? ? ? ? this.outputFileName = outputFileName; ? ? ? ? ? ? // 設(shè)置圖片長寬 ?? ? ? ? ? setWidthAndHeight(width, height); ? ? ? ? ? ? // 是否是等比縮放 標(biāo)記 ? ? ? ? ? ? this.proportion = gp; ? ? ? ? ? ? return compressPic(); ? ? ? ? } ? ?? ? ? /** ? ? ?* 圖片壓縮 ? ? ?* @param downloadUrl ? ? ?* @param inputDir ? ? ?* @param outDir ? ? ?* @return ? ? ?*/ ? ? public String ImageCompression(String downloadUrl,String inputDir,String outDir){ ? ? ?? ? ? ? ?? ?Random rnd = new Random(); ? ? ?? ?String picName = downloadUrl.substring(downloadUrl.lastIndexOf("/")+1); ? ? ?? ?String extendName =""; ?? ??? ?String beforeName= ""; ?? ??? ? ?? ??? ?if(picName.contains(".")){ ?? ??? ??? ? extendName = picName.substring(picName.indexOf(".")); ?? ??? ??? ? beforeName= picName.substring(0,picName.indexOf(".")); ?? ??? ?}else{ ?? ??? ??? ? extendName = picName; ?? ??? ??? ? beforeName= picName; ?? ??? ?} ?? ??? ? ?? ??? ?//隨機(jī)數(shù) ?? ??? ?Integer r = rnd.nextInt(1000); ?? ??? ?beforeName = new CompressPic().getPinYinHeadChar(beforeName); ?? ??? ?long ts = System.currentTimeMillis(); ?? ??? ?String outpicName=ts+beforeName+r+".jpg"; ?? ??? ?outpicName = outpicName.replace("%", ""); ?? ??? ?if(outpicName.contains("張棟杰總經(jīng)理會見旭陽集團(tuán)董事長楊雪崗")){ ?? ??? ??? ?outpicName="zdjzjlhjxyjtdszyxg.jpg"; ?? ??? ?} ?? ??? ? ? ? ?? ?if(httpDownload(downloadUrl, inputDir, outpicName)){ ? ? ?? ??? ?// 當(dāng)前時間 ? ? ? ? ? ? // String curTime = new Long(System.currentTimeMillis()).toString(); ? ? ? ? ? ? this.compressPic(inputDir, outDir, outpicName, outpicName, 300, 150, true); ? ? ? ? ? ? return outpicName; ? ? ? ? }else { ?? ??? ??? ?return null; ?? ??? ?} ? ? } ? ?? ? ? /** ? ? ?* http圖片下載 ? ? ?* @param httpUrl ? ? ?* @param saveFile ? ? ?* @return ? ? ?*/ ? ? public static boolean httpDownload(String httpUrl,String saveDir,String saveName){ ? ? ?? ?// 下載網(wǎng)絡(luò)文件 ? ? ?? ?int bytesum = 0; ? ? ?? ?int byteread = 0; ? ? ?? ?URL url = null; ? ? ? ? ? try { ? ? ? ? ? ? url = new URL(httpUrl); ? ? ? ? ? } catch (MalformedURLException e1) { ? ? ? ? ? ? ? e1.printStackTrace(); ? ? ? ? ? ? return false; ? ? ? ? ? } ? ? ? ? // 存儲目錄 ? ? ? ? File outDir = new File(saveDir); ? ? ? ? if(!outDir.exists()){ ? ? ? ? ?? ?outDir.mkdirs(); ? ? ? ? } ? ? ? ? try { ? ? ? ? ?? ?URLConnection conn = url.openConnection(); ? ? ? ? ?? ?InputStream inStream = conn.getInputStream(); ? ? ? ? ?? ?FileOutputStream fs = new FileOutputStream(saveDir+saveName); ? ? ? ? ?? ? ? ? ? ? ?? ?byte[] buffer = new byte[1204]; ? ? ? ? ?? ?while ((byteread = inStream.read(buffer)) != -1) { ? ? ? ? ?? ??? ?bytesum += byteread; ? ? ? ? ?? ??? ?fs.write(buffer, 0, byteread); ? ? ? ? ?? ?} ? ? ? ? ?? ?fs.close(); ? ? ? ? ?? ?inStream.close(); ? ? ? ? } catch (FileNotFoundException e) { ? ? ? ? ?? ?e.printStackTrace(); ? ? ? ? ?? ?return false; ? ? ? ? } catch (IOException e) { ? ? ? ? ?? ?e.printStackTrace(); ? ? ? ? ?? ?return false; ? ? ? ? } ? ? ? ? return true; ? ? } ? ? /**? ? ? ?* 提取每個漢字的首字母? ? ? ?* ? ? ? ?* @param str? ? ? ?* @return String? ? ? ?*/ ? ? ? public ?String getPinYinHeadChar(String str) { ? ? ? ? ? String convert = ""; ? ? ? ? ? for (int j = 0; j < str.length(); j++) { ? ? ? ? ? ? ? char word = str.charAt(j); ? ? ? ? ? ? ? // 提取漢字的首字母 ? ? ? ? ? ? ? String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word); ? ? ? ? ? ? ? if (pinyinArray != null) { ? ? ? ? ? ? ? ? ? convert += pinyinArray[0].charAt(0); ? ? ? ? ? ? ? } else { ? ? ? ? ? ? ? ? ? convert += word; ? ? ? ? ? ? ? } ? ? ? ? ? } ? ? ? ? ? return convert; ? ? ? } ? ? ? public static void main(String[] arg) { ? ? ? ? CompressPic mypic = new CompressPic(); ?? ??? ?mypic.compressPic("C:\\Users\\mazhaoxu\\Desktop\\", "C:\\Users\\mazhaoxu\\Desktop\\", "微信圖片_20180712182800.png", "2019061818542824511111111111.png"); // ? ? ? ?if(httpDownload("http://221.195.72.44:8122/NR/rdonlyres/B5071DE7-9652-44AF-9534-0EE0ED2DCA92/15177/resource_651768621.jpg", "D:\\data\\resource_651768621.jpg")){ // ? ? ? ? ? ?int start = (int) System.currentTimeMillis(); ? // 開始時間 // ? ? ? ? ? ?mypic.compressPic("D:\\data\\", "D:\\data\\", "resource_651768621.jpg", "r1"+start+".jpg", 250, 250, true); // ? ? ? ?} // ? ? ? String s= ?mypic.getPinYinHeadChar("http://114.251.186.42:81/web-s/images/1447069462915xfydh1_fb_fb521.jpg"); // ? ? ? ?mypic.ImageCompression("http://114.251.186.42:81/web-s/images/mobile/1447069462915xfydh1_fb_fb521.jpg","d:\\images\\", "d:\\images\\mobile\\"); // ? ? ? ?mypic.compressPic("d:\\", "d:\\image\\mobile", "144921941137520151204fgw1747.jpg", "144921941137520151204fgw1747.jpg"); // ? ? ? ?String s = "/image/dslfsjss/image/sisis /image"; // ? ??? ??? ?System.out.println(s.replace("/image/", "/mobile/image/")); ? ? } ? ? ?? ?/** ?? ? * 獲取圖片寬度 ?? ? * @param file ?圖片文件 ?? ? * @return 寬度 ?? ? */ ?? ?public static int getImgWidth(File file) { ?? ??? ?InputStream is = null; ?? ??? ?BufferedImage src = null; ?? ??? ?int ret = -1; ?? ??? ?try { ?? ??? ??? ?is = new FileInputStream(file); ?? ??? ??? ?src = javax.imageio.ImageIO.read(is); ?? ??? ??? ?ret = src.getWidth(null); // 得到源圖寬 ?? ??? ??? ?is.close(); ?? ??? ?} catch (Exception e) { ?? ??? ??? ?e.printStackTrace(); ?? ??? ?} ?? ??? ?return ret; ?? ?} ?? ?/** ?? ? * 獲取圖片高度 ?? ? * @param file ?圖片文件 ?? ? * @return 高度 ?? ? */ ?? ?public static int getImgHeight(File file) { ?? ??? ?InputStream is = null; ?? ??? ?BufferedImage src = null; ?? ??? ?int ret = -1; ?? ??? ?try { ?? ??? ??? ?is = new FileInputStream(file); ?? ??? ??? ?src = javax.imageio.ImageIO.read(is); ?? ??? ??? ?ret = src.getHeight(null); // 得到源圖高 ?? ??? ??? ?is.close(); ?? ??? ?} catch (Exception e) { ?? ??? ??? ?e.printStackTrace(); ?? ??? ?} ?? ??? ?return ret; ?? ?} ?} ?
這是我用的工具類,其中里面業(yè)務(wù)會用到pinyin4j的jar包,和圖片壓縮關(guān)系不大,可以去除,我是因?yàn)楸容^著急改完,就沒動,如果不想改,需要引入pinyin4j的jar包。
maven:
<!-- https://mvnrepository.com/artifact/com.belerweb/pinyin4j --> ?? ??? ?<dependency> ?? ??? ??? ?<groupId>com.belerweb</groupId> ?? ??? ??? ?<artifactId>pinyin4j</artifactId> ?? ??? ??? ?<version>2.5.0</version> </dependency>
可以自行用上面工具類里的main方法進(jìn)行測試
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- 詳解Java實(shí)現(xiàn)批量壓縮圖片裁剪壓縮多種尺寸縮略圖一鍵批量上傳圖片
- java input 調(diào)用手機(jī)相機(jī)和本地照片上傳圖片到服務(wù)器然后壓縮的方法
- java實(shí)現(xiàn)上傳圖片并壓縮圖片大小功能
- Java中上傳圖片壓縮處理的方法示例
- Java實(shí)現(xiàn)的上傳并壓縮圖片功能【可等比例壓縮或原尺寸壓縮】
- java實(shí)現(xiàn)文件上傳下載和圖片壓縮代碼示例
- 簡單實(shí)現(xiàn)java上傳圖片文件功能
- Java Servlet上傳圖片到指定文件夾并顯示圖片
- Android實(shí)現(xiàn)上傳圖片至java服務(wù)器
相關(guān)文章
SpringBoot整合Lucene實(shí)現(xiàn)全文檢索的詳細(xì)步驟
全文搜索(Full-Text?Search)是指對大規(guī)模存儲在計算機(jī)系統(tǒng)中的文本數(shù)據(jù)進(jìn)行檢索和匹配的技術(shù),它允許用戶輸入關(guān)鍵字,然后從海量的文本數(shù)據(jù)中快速找到相關(guān)的信息,本文介紹了SpringBoot整合Lucene實(shí)現(xiàn)全文檢索的詳細(xì)步驟,需要的朋友可以參考下2024-03-03Mybatis-Plus saveBatch()批量保存失效的解決
本文主要介紹了Mybatis-Plus saveBatch()批量保存失效的解決,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-01-01SpringBoot使用@Cacheable注解實(shí)現(xiàn)緩存功能流程詳解
最近一直再學(xué)Spring Boot,在學(xué)習(xí)的過程中也有過很多疑問。為了解答自己的疑惑,也在網(wǎng)上查了一些資料,以下是對@Cacheable注解的一些理解2023-01-01RocketMQ?broker?消息投遞流程處理PULL_MESSAGE請求解析
這篇文章主要為大家介紹了RocketMQ?broker?消息投遞流程處理PULL_MESSAGE請求源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04