溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

利用java怎么將base64字符串轉(zhuǎn)換為圖片

發(fā)布時(shí)間:2021-02-22 15:44:32 來(lái)源:億速云 閱讀:1307 作者:Leah 欄目:編程語(yǔ)言

這篇文章給大家介紹利用java怎么將base64字符串轉(zhuǎn)換為圖片,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

Java可以用來(lái)干什么

Java主要應(yīng)用于:1. web開(kāi)發(fā);2. Android開(kāi)發(fā);3. 客戶端開(kāi)發(fā);4. 網(wǎng)頁(yè)開(kāi)發(fā);5. 企業(yè)級(jí)應(yīng)用開(kāi)發(fā);6. Java大數(shù)據(jù)開(kāi)發(fā);7.游戲開(kāi)發(fā)等。

1. 圖片轉(zhuǎn)base64字符串:

 /**
  * base64編碼字符串轉(zhuǎn)換為圖片
  * @param imgStr base64編碼字符串
  * @param path 圖片路徑
  * @return
  */
 public static boolean base64StrToImage(String imgStr, String path) {
  if (imgStr == null)
  return false;
  BASE64Decoder decoder = new BASE64Decoder();
  try {
   // 解密
   byte[] b = decoder.decodeBuffer(imgStr);
   // 處理數(shù)據(jù)
   for (int i = 0; i < b.length; ++i) {
    if (b[i] < 0) {
     b[i] += 256;
    }
   }
   //文件夾不存在則自動(dòng)創(chuàng)建
   File tempFile = new File(path);
   if (!tempFile.getParentFile().exists()) {
    tempFile.getParentFile().mkdirs();
   }
   OutputStream out = new FileOutputStream(tempFile);
   out.write(b);
   out.flush();
   out.close();
   return true;
  } catch (Exception e) {
   return false;
  }
 }

2. base64字符串轉(zhuǎn)圖片:

 /**
  * 圖片轉(zhuǎn)base64字符串
  * @param imgFile 圖片路徑
  * @return
  */
 public static String imageToBase64Str(String imgFile) {
  InputStream inputStream = null;
  byte[] data = null;
  try {
   inputStream = new FileInputStream(imgFile);
   data = new byte[inputStream.available()];
   inputStream.read(data);
   inputStream.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
  // 加密
  BASE64Encoder encoder = new BASE64Encoder();
  return encoder.encode(data);
 }

3. 測(cè)試:

public static void main(String[] args) {
  String base64Str = imageToBase64Str("D:/pic/001.jpg");
  System.out.println(base64Str);
  
  boolean b = base64StrToImage(base64Str, "D:/pic/temp/002.jpg");
  System.out.println(b);
 }

關(guān)于利用java怎么將base64字符串轉(zhuǎn)換為圖片就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI