Exception in thread "main" javax.imageio.IIOException: Can't read input file!

背景概述:最近在寫連鎖超市的項目其中遇到了不少坑,其中接下來就是其中一個 ,望道友們有幫助java

報錯提示

Exception in thread "main" javax.imageio.IIOException: Can't read input file! 複製代碼

寫的程序以下 :

public static void main(String[] args) throws IOException {
   
        String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        Thumbnails.of(new File("D:\\zhangxiyu.jpg"))
                .size(200,200).watermark(Positions.BOTTOM_RIGHT,
                ImageIO.read(new File(basePath+"/watermark.jpg")),0.25f).outputQuality(0.8f)
                .toFile("D:\\zhangxiyunew.jpg");
    }
複製代碼

解決 問題

  • 查閱不少資料後發現問題以下
在java中獲取文件路徑的時候,有時候會獲取到空格,可是在中文編碼環境下,空格會變成「%20」從而使得路徑錯誤
複製代碼
  • 解決方法

1:) TestURL().class.getResource("").getPath()或TestURL().class.getResource("").getFile()得到的路徑,不能被FileReader()和FileWriter()直接應用。緣由是URL對空格,特殊字符(%,#,[]等)和中文進行了編碼處理。 例如:空格變爲%20。有解決方法(1),使用repaceAll("%20",'')替換後,只能解決空格問題。可是路徑中包含%和中文就不行了。bash

2:) 使用URLDecoder.decode(str,"UTF-8")解碼,可是隻能解決一部分,若路徑中含有+,也是不能解決的,緣由是URL並非徹底用URLEncoder.encode(str,"UTF-8")編碼的,+號被解碼後,卻變成了空格。編碼

3:) 能夠解決全部的問題,用TestURL().class.getResource("").toURI().getPath(),可是須要處理URISyntaxException異常,比較麻煩點。spa

  • 總結解決方法
path=URLDecoder.decode(path,"utf-8");//關鍵啊 ! 
複製代碼
  • 如上方法是把空格給轉化了 就能夠了

更改代碼以下

private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();

  static{
        try {
              basePath = URLDecoder.decode(basePath,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
複製代碼
所有代碼爲
//經過線程的反向推導出calsspath的路徑
    private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();

  static{
        try {
              basePath = URLDecoder.decode(basePath,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws IOException {

        String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
        Thumbnails.of(new File("D:\\zhangxiyu.jpg"))
                .size(200,200).watermark(Positions.BOTTOM_RIGHT,
                ImageIO.read(new File(basePath+"/watermark.jpg")),0.25f).outputQuality(0.8f)
                .toFile("D:\\zhangxiyunew.jpg");
    }
}
複製代碼
資料參考連接爲
希冀能夠幫得上各位道友,加油道友們!!!
相關文章
相關標籤/搜索