使用Base64將圖片轉化爲字符串(後期詳細整理)

需要導入sun.misc.BASE64Decoder.jar包

Base64ToImage.java

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class Base64ToImage {
//  替換字符串
  public String changeStr(String oldStr, String newStr, String str) {
      return str.replace(oldStr, newStr);
  }
  /**
   * 
   * @功能:創建一個目錄,並在此目錄下生成圖片
   * @時間:2017年3月7日 下午8:38:21
   * @param path 原Base64字符串存放的目錄
   * @param targetPath 生成圖片的父目錄
   * @param dirName 生成圖片的目錄名
 * @throws IOException 
   */
  public void readStrToImg(String path,String targetPath,String dirName){
      File file = new File(path);
//    目標目錄
    File targetFile=new File(targetPath+"\\"+dirName);
//    創建一個名稱爲dirName的目錄
    targetFile.mkdir();
    targetPath=targetPath+"\\"+dirName;
    File[] array = file.listFiles();
    for (int i = 0; i < array.length; i++) {
        if (array[i].isFile()) {
//            去掉txt文件的擴展名,值得到文件名
            String fileName=array[i].getName().substring(0, array[i].getName().length()-3);
//            新建一個文件,用來存儲Base64字符串,並且文件的名稱要與圖片的名稱一致
            try {
                GenerateImage(readStr(array[i].getPath()),targetPath,fileName);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
    System.out.println("完成!");
  }
  /**
   * 
   * @功能:根據路徑,讀取文件的內容,返回字符串
   * @時間:2017年3月7日 下午8:44:02
   * @param path 這個文件的路徑
   * @return
 * @throws IOException 
   */
  public String readStr(String path) throws IOException{
      InputStream is=new FileInputStream(path);
      InputStreamReader isr=new InputStreamReader(is);
      BufferedReader br=new BufferedReader(isr);
      String str="";
      int flag=0;
      br.mark(flag);
      while(br.ready()){
          br.reset();
          str+=br.readLine();
          br.mark(flag);
      }
      br.close();
      isr.close();
      is.close();
    return changeStr("/","*",str);
  }
  //base64字符串轉化成圖片
  public boolean GenerateImage(String imgStr,String targetPath,String imageName)
  {   //對字節數組字符串進行Base64解碼並生成圖片
      if (imgStr == null) //圖像數據爲空
          return false;
      Decoder.BASE64Decoder decoder = new Decoder.BASE64Decoder();
      try 
      {
          //Base64解碼
          byte[] b = decoder.decodeBuffer(imgStr);
          for(int i=0;i<b.length;++i)
          {
              if(b[i]<0)
              {//調整異常數據
                  b[i]+=256;
              }
          }
          //生成jpeg圖片
          String imgFilePath = targetPath+"\\"+imageName;//新生成的圖片
          OutputStream out = new FileOutputStream(imgFilePath);    
          out.write(b);
          out.flush();
          out.close();
          return true;
      } 
      catch (Exception e) 
      {
          return false;
      }
  }
}

ImageToBase64 .java

import java.io.File;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ImageToBase64 
{

//    替換字符串
    public String changeStr(String oldStr, String newStr, String str) {
        return str.replace(oldStr, newStr);
    }

    /**
     * 
     * @功能:創建一個目錄,並且在此目錄下創建生成的Base64碼的文件
     * @時間:2017年3月7日 下午6:27:48
     * @param path 圖片的路徑
     * @param targetPath Base64字符串存放的路徑
     * @param dirName 存放Base64字符串的文件的名稱
     */
    public void writeStrToFile(String path,String targetPath,String dirName) {
        File file = new File(path);
//        目標目錄
        File targetFile=new File(targetPath+"\\"+dirName);
//        創建一個名稱爲dirName的目錄
        targetFile.mkdir();
        File[] array = file.listFiles();
        for (int i = 0; i < array.length; i++) {
            if (array[i].isFile()) {
//                新建一個文件,用來存儲Base64字符串,並且文件的名稱要與圖片的名稱一致
                writeStr(GetImageStr(array[i].getPath()),targetFile+"\\"+array[i].getName()+".txt");
            }

        }
        System.out.println("完成!");
    }
    /**
     * 
     * @功能:將base64編碼寫入到txt文件中
     * @時間:2017年3月7日 下午6:46:20
     * @param path
     * @param str
     */
    public void writeStr(String imageStr,String targetPath){
        String imgFilePath = targetPath;//新生成的圖片
        byte[] bytes=imageStr.getBytes();
        OutputStream out = null;
        try {
            out = new FileOutputStream(imgFilePath);
            out.write(bytes);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }    
        try {
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    /**
     * 
     * @功能:圖片轉化成base64字符串
     * @時間:2017年3月7日 下午8:37:35
     * @param path
     * @return
     */
    public String GetImageStr(String path)
    {//將圖片文件轉化爲字節數組字符串,並對其進行Base64編碼處理
        InputStream in = null;
        byte[] data = null;
        //讀取圖片字節數組
        try 
        {
            in = new FileInputStream(path);        
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }
        //對字節數組Base64編碼
        Decoder.BASE64Encoder encoder = new Decoder.BASE64Encoder();
        return changeStr("/","*",encoder.encode(data));//將編碼中/全部替換成*後返回Base64編碼過的字節數組字符串

    }


}

Test.java

import java.util.Scanner;

import sjj.base64.Base64ToImage;
import sjj.base64.ImageToBase64;

public class Test {

    public static void main(String[] args) {
        String path="";
        String targetPath="";
        String fileName="";
        int flag=0;
        System.out.println("1.圖片轉化爲字符串\r\n2.字符串轉化爲圖片");
        Scanner scan=new Scanner(System.in);
        flag=scan.nextInt();
        if(flag==1){
            ImageToBase64 itb=new ImageToBase64();
            System.out.println("輸入源圖片的路徑:");
            path=scan.next();
            System.out.println("輸入字符串存放的路徑:");
            targetPath=scan.next();
            System.out.println("輸入存放字符串的目錄的名稱:");
            fileName=scan.next();
            itb.writeStrToFile(path, targetPath, fileName);
        }else if(flag==2){
            Base64ToImage bti=new Base64ToImage();
            System.out.println("輸入源字符串的路徑:");
            path=scan.next();
            System.out.println("輸入圖片存放的路徑:");
            targetPath=scan.next();
            System.out.println("輸入存放圖片的目錄的名稱:");
            fileName=scan.next();
            bti.readStrToImg(path, targetPath, fileName);
        }else{
            System.out.println("程序結束!");
        }
    }

}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章