Java圖片讀取ImageIO.read()報錯問題及解決
更新時間:2024年10月15日 15:47:18 作者:刀下陽光
在使用imageio庫讀取圖片時,如果路徑中包含中文,可能會導致讀取失敗,解決方法是將路徑中的中文字符進行轉義處理,可以使用ImageUtil.java工具類進行路徑轉義,從而避免錯誤,這是一個常見問題,希望本文的解決方案能幫助到遇到相同問題的開發(fā)者
使用imageio直接讀取圖片報錯問題重現(xiàn)
原因分析
路徑中包含中文解決方案:
將路徑中的中文進行轉義
URLEncoder.encode(fileName,"UTF-8")
ImageUtil.java工具類:
package com.test.common.utils; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; public class ImageUtil { /** * 描述:將圖片地址進行base64編碼 */ public static String encodeImgageToBase64(URL imageUrl) {// 將圖片文件轉化為字節(jié)數(shù)組字符串,并對其進行Base64編碼處理 ByteArrayOutputStream outputStream = null; try { BufferedImage bufferedImage = ImageIO.read(imageUrl); outputStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "jpg", outputStream); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 對字節(jié)數(shù)組Base64編碼 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(outputStream.toByteArray());// 返回Base64編碼過的字節(jié)數(shù)組字符串 } /** * 描述:將圖片文件進行base64編碼 */ public static String encodeImgageToBase64(File imageFile) {// 將圖片文件轉化為字節(jié)數(shù)組字符串,并對其進行Base64編碼處理 ByteArrayOutputStream outputStream = null; try { BufferedImage bufferedImage = ImageIO.read(imageFile); outputStream = new ByteArrayOutputStream(); ImageIO.write(bufferedImage, "jpg", outputStream); } catch (MalformedURLException e1) { e1.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } // 對字節(jié)數(shù)組Base64編碼 BASE64Encoder encoder = new BASE64Encoder(); return encoder.encode(outputStream.toByteArray());// 返回Base64編碼過的字節(jié)數(shù)組字符串 } /** * 描述:將base64圖片解碼并保存 */ public static File decodeBase64ToImage(String base64, String path, String imgName) { BASE64Decoder decoder = new BASE64Decoder(); File file=null; try { file=new File(path + imgName); FileOutputStream write = new FileOutputStream(file); String replase=base64.replace("data:image/jpeg;base64,",""); byte[] decoderBytes = decoder.decodeBuffer(replase); write.write(decoderBytes); write.close(); } catch (IOException e) { e.printStackTrace(); } return file; } }
總結
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Spring Boot2深入分析解決java.lang.ArrayStoreException異常
這篇文章介紹了Spring Boot2深入分析解決java.lang.ArrayStoreException異常的方法,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-12-12使用Jenkins Pipeline自動化構建發(fā)布Java項目的方法
這篇文章主要介紹了使用Jenkins Pipeline自動化構建發(fā)布Java項目的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-04-04Jpa?Specification如何實現(xiàn)and和or同時使用查詢
這篇文章主要介紹了Jpa?Specification如何實現(xiàn)and和or同時使用查詢,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11解決本機安裝的JDK8,啟動IDEA2019沒反應的問題(開發(fā)工具)
這篇文章主要介紹了解決本機安裝的JDK8啟動IDEA2019沒反應的問題(開發(fā)工具),非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2019-10-10