Java processing in the interface returns base64 encoded image data

  In doing interface test of time, some of the returned interface content encryption is a large section of text. In this case, there may be a picture of encrypted data back, you need to convert these data into images saved view.

E.g:

  

 

 

   Here, we can see the beginning of the corresponding key Content There "data: image / jpeg; base64," the words. We simply believe that this is a jpeg format pictures, and encoded in base64.

  By JPath, we can take a direct return to the Content, and then remove the front "data: image / jpeg; base64," it is the actual return of data.

// Returns Content data acquired in json
String Content = JSONPath.read (json, "$ .content" ) .toString ());
// remove the front "data: image / jpeg; base64 ," the words String imgdata
= content.replace ( "Data: Image / JPEG; Base64,", "" ) // decode Base64 Base64Decoder decoder = new new Base64Decoder (); byte [] = Data decoder.decodeBuffer (imgdata); for ( int I = 0; I <data.length; I ++ ) { IF (Data [I] <0 ) { Data [I] + = 256 ; } }
// write saved as a jpeg file, a FileOutputStream fos
= new new FileOutputStream ("D:\\test.jpg"); fos.write(data); fos.flush(); fos.close();

  Of course, there will be a plus decoding encoded. If we want to add a picture file is encoded into base64, you can refer to the following code:

public static String getImageStr(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);
}

  This allows you to convert images into base64 encoded string.

  If the direct use of the code above should not be successful . The reason is that the use of encryption and decryption are Base64 and Base64Decoder BASE64Encoder under sun.misc packet sun.misc.BASE64Encoder / BASE64Decoder class.

  This class is an internal sun's method, and no disclosure in the Java API, not visible JDK standard library, but contains the class in the JDK, can be used directly. But directly in Eclipse, but you can not find the class. Solutions are as follows:

  1. Right Project - "Build Path -" Configure Build Path

  Select Libraries, click the JRE System Library, select the Access rules, if the rule is not defined before, will show No rules defined

 

   2. Access rules, click Edit - "Add, then click Ok

 

   3. Select Accessible in Resolution drop-down list box, Rule Pattern Select **, then click ok

 

  

 

  After this operation, we can successfully use a Base64-related classes.

Guess you like

Origin www.cnblogs.com/generalli2019/p/11465132.html