天天看點

java讀取網絡圖檔怎麼寫

本以為是個非常簡單的問題,實際試了卻發現不是那麼回事,真有點麻煩。

那些​​

​URL​

​​、​

​URI​

​​、​

​File​

​等class,處理網絡圖檔時總是報錯,但本地圖檔就可以。

找到了一個看起來還算優雅的辦法,直接上代碼:

package image;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author zhaosen
 * @date 2021年8月3日
 * 由于java 讀取網絡圖檔很麻煩,在網上找到了這個辦法,覺得還行
 */
public class ImageHelper {

    /**
     * 将圖檔寫入到磁盤
     *
     * @param img 圖檔資料流
     * @param zipImageUrl 檔案儲存時的名稱
     */
    public static void writeImageToDisk(byte[] img, String zipImageUrl) {
        try {
            File file = new File(zipImageUrl);
            FileOutputStream fops = new FileOutputStream(file);
            fops.write(img);
            fops.flush();
            fops.close();
            System.out.println("圖檔已經寫入" + zipImageUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();// 通過輸入流擷取圖檔資料
            byte[] btImg = readInputStream(inStream);// 得到圖檔的二進制資料
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 從輸入流中擷取資料
     *
     * @param inStream 輸入流
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }


}
      
import image.ImageHelper;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.UUID;

public class Starter {

    public static void main(String[] args) throws IOException, URISyntaxException {

        //如果圖檔檔案不是本地的,是網絡圖檔,怎麼辦?
        //ps: 沒想到java讀取網絡圖檔還真有點麻煩
        //讀取網絡圖檔
        //java讀取和處理網絡圖檔還真麻煩 屮。 不得不轉為本地檔案處理
        String imageUrl = "https://img-home.csdnimg.cn/images/20201120101655.png";
        int index = imageUrl.lastIndexOf(".");
        if (index == -1) {
            return;
        }
        String extName = imageUrl.substring(index + 1);

        byte[] imgByteArr = ImageHelper.getImageFromNetByUrl(imageUrl);
        String uuid = UUID.randomUUID().toString();
        String localFileName = String.format("%s.%s", uuid, extName);
        ImageHelper.writeImageToDisk(imgByteArr, localFileName);

        File localTempFile = new File(localFileName);

        //删除臨時檔案
        localTempFile.delete();
    }


}