image to base64/md5

记录 2023-06-29

图片内容的base64编码
图片内容(base64编码前)的md5值

public void Test(String imagePath) {
    String imagePath = messageReq.getImagePath();
    byte[] imageBytes;
    // 图片内容的base64编码
    String base64 = null;
    // 图片内容(base64编码前)的md5值
    String md5 = null;
    try {
        if (imagePath.startsWith("http")) {
            // imageBytes = netWorkImage9(imagePath);
            imageBytes = netWorkImage(imagePath);
        } else {
            // imageBytes = localImage9(imagePath);
            imageBytes = localImage(imagePath);
        }
        base64 = Base64.getEncoder().encodeToString(imageBytes);
        md5 = DigestUtils.md5Hex(imageBytes);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
@NotNull
private byte[] netWorkImage9(String imageUrl) throws IOException {
    URL url = new URL(imageUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        try (InputStream inputStream = connection.getInputStream()) {
            // readAllBytes 为jdk9中新出的方法
            return inputStream.readAllBytes();
        }
    }
    throw new IOException("图片下载失败: " + imageUrl);
}


@NotNull
private byte[] netWorkImage(String imageUrl) throws IOException {
    URL url = new URL(imageUrl);
    HttpURLConnection connection = (HttpURLConnection) url.openConnection();
    connection.setRequestMethod("GET");
    if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
        try (InputStream inputStream = connection.getInputStream(); ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[inputStream.available()];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toByteArray();
        }

    }
    throw new IOException("图片下载失败: " + imageUrl);
}
@NotNull
private byte[] localImage9(String imagePath) throws IOException {
    Path path = Paths.get(imagePath);
	// readAllBytes 为jdk9中新出的方法
    return Files.readAllBytes(path);
}


@NotNull
private byte[] localImage(String imagePath) throws IOException {
    try (InputStream inputStream = new FileInputStream(imagePath); ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
        byte[] buffer = new byte[inputStream.available()];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        return outputStream.toByteArray();
    }
}