簡體   English   中英

在Java中將base64字符串轉換為服務器端的圖像

[英]Convert base64 string to image at server side in java

我有base64字符串,無論服務器端的圖像格式如何,我都希望將其轉換回圖像。 我通過使用以下代碼進行了嘗試,正在創建圖像,但是當我嘗試預覽時,顯示錯誤無法加載圖像。

public void convertStringToImage(String base64) {
        try {
            byte[] imageByteArray = decodeImage(base64);

            FileOutputStream imageOutFile = new FileOutputStream("./src/main/resources/demo.jpg");
            imageOutFile.write(imageByteArray);
            imageOutFile.close();
        } catch (Exception e) {
            logger.log(Level.SEVERE, "ImageStoreManager::convertStringToImage()" + e);
        }
    }


    public static byte[] decodeImage(String imageDataString) {
        return Base64.decodeBase64(imageDataString);
    }

我應該怎么做才能使我的圖像看起來正確?

您的代碼看起來不錯。 但我可以為您建議更多調試步驟。

  1. 使用此網頁手動編碼文件
  2. 比較String base64包含與您在頁面上看到的內容完全相同的內容。 //如果此處出現問題,則您的請求已損壞,也許前端有一些編碼問題?
  3. 查看在./src/main/resources/demo.jpg下創建的文件內容,並比較內容(大小,二進制比較)//如果此處出現問題,您將知道實際上保存操作已損壞

備注:

  • 您是否嘗試在關閉之前執行.flush()
  • 當前形式的代碼可能會導致資源泄漏,請看一下try-with-resources

嘗試這個:

public static byte[] decodeImage(String imageDataString) {
    return org.apache.commons.codec.binary.Base64.decodeBase64(imageDataString.getBytes());
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM