如何将图像转换为Base64字符串?

时间:2022-11-13 12:22:15

Can someone tell me the code to transform a image (maximum of 200KB) into Base64 String?

有人能告诉我将图像(最大200KB)转换成Base64字符串的代码吗?

I need to know how to do it with android, because I have to add the functionality to upload images to a remote server in my main app putting them into a row of the database, as a string.

我需要知道如何使用android,因为我必须添加将图片上传到主应用中的远程服务器的功能,将它们作为字符串放到数据库的一行中。

I am searching in google and in * but I could not find easy examples that I can afford and also I find some examples but they are not talking about to transform into String. Then I need to transform into string to upload by JSON to my remote server.

我正在谷歌和*中搜索但是我找不到我能负担得起的简单示例,我也找到了一些示例,但它们并不是要转换成字符串。然后我需要转换成字符串,通过JSON上传到我的远程服务器。

9 个解决方案

#1


280  

You can use the Base64 Android class:

你可以使用Base64 Android类:

String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

You'll have to convert your image into a byte array though. Here's an example:

不过,您必须将您的图像转换成字节数组。这里有一个例子:

Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray(); 

* Update *

*更新*

If you're using an older SDK library (because you want it to work on phones with older versions of the OS) you won't have the Base64 class packaged in (since it just came out in API level 8 aka version 2.2).

如果您正在使用一个较旧的SDK库(因为您想让它在使用较旧OS版本的手机上工作),那么就不会打包Base64类(因为它刚刚出现在API级别8,即2.2版本中)。

Check this article out for a work-around:

看看这篇文章,你会发现:

http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html

http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html

#2


85  

Instead of using Bitmap, you can also do this through trivial InputStream. Well I am not sure, but I think its a bit efficient

除了使用位图,您还可以通过普通的InputStream来实现这一点。我不确定,但我认为这有点有效率

InputStream inputStream = new FileInputStream(fileName);//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
    while ((bytesRead = inputStream.read(buffer)) != -1) {
    output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);

#3


6  

If you need base64 over JSON, check out Jackson: it has explicit support for binary data read/write as base64 at both low level (JsonParser, JsonGenerator) and data-binding level. So you can just have POJOs with byte[] properties, and encoding/decoding is automatically handled. And pretty efficiently too, should that matter.

如果需要base64而不是JSON,请查看Jackson:它在低级别(JsonParser, JsonGenerator)和数据绑定级别上都明确支持二进制数据读/写作为base64。因此,您可以使用带有byte[]属性的pojo,并自动处理编码/解码。而且效率也很高。

#4


3  

this code prefect run in my project

这段代码在我的项目中运行

profile_image.buildDrawingCache();
                Bitmap bmap = profile_image.getDrawingCache();
                String encodedImageData =getEncoded64ImageStringFromBitmap(bmap);


public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    byte[] byteFormat = stream.toByteArray();
    // get the base 64 string
    String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);

    return imgString;
}

#5


3  

// put the image file path into this method
  public static String getFileToByte(String filePath){
      Bitmap bmp = null;
      ByteArrayOutputStream bos = null;
      byte[] bt = null;
      String encodeString = null;
       try{
        bmp = BitmapFactory.decodeFile(filePath);
        bos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos); 
        bt = bos.toByteArray();
        encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
      }catch (Exception e){
        e.printStackTrace();
      }
      return encodeString;
}

#6


2  

If you're doing this on Android, here's a helper copied from the React Native codebase:

如果你在Android上做这个,这里有一个从React Native codebase复制的助手:

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;

// You probably don't want to do this with large files
// (will allocate a large string and can cause an OOM crash).
private String readFileAsBase64String(String path) {
  try {
    InputStream is = new FileInputStream(path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
    byte[] buffer = new byte[8192];
    int bytesRead;
    try {
      while ((bytesRead = is.read(buffer)) > -1) {
        b64os.write(buffer, 0, bytesRead);
      }
      return baos.toString();
    } catch (IOException e) {
      Log.e(TAG, "Cannot read file " + path, e);
      // Or throw if you prefer
      return "";
    } finally {
      closeQuietly(is);
      closeQuietly(b64os); // This also closes baos
    }
  } catch (FileNotFoundException e) {
    Log.e(TAG, "File not found " + path, e);
    // Or throw if you prefer
    return "";
  }
}

private static void closeQuietly(Closeable closeable) {
  try {
    closeable.close();
  } catch (IOException e) {
  }
}

#7


0  

byte[] decodedString = Base64.decode(result.getBytes(), Base64.DEFAULT);

#8


0  

Below are the pseudo code that may help you :

下面是伪代码,可以帮助您:

public  String getBase64FromFile(String path)
      { 
         Bitmap bmp = null; 
         ByteArrayOutputStream baos = null;  
         byte[] baat = null;
         String encodeString = null;  
         try
          {   
            bmp = BitmapFactory.decodeFile(path);     
            baos = new ByteArrayOutputStream();                 
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            baat = baos.toByteArray(); 
            encodeString = Base64.encodeToString(baat, Base64.DEFAULT);
          }
          catch (Exception e)
          { 
           e.printStackTrace();  
          }  

        return encodeString;
     }

#9


-1  

Use this Code:

使用这段代码:

byte[ ] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);

Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

#1


280  

You can use the Base64 Android class:

你可以使用Base64 Android类:

String encodedImage = Base64.encodeToString(byteArrayImage, Base64.DEFAULT);

You'll have to convert your image into a byte array though. Here's an example:

不过,您必须将您的图像转换成字节数组。这里有一个例子:

Bitmap bm = BitmapFactory.decodeFile("/path/to/image.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();  
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object   
byte[] b = baos.toByteArray(); 

* Update *

*更新*

If you're using an older SDK library (because you want it to work on phones with older versions of the OS) you won't have the Base64 class packaged in (since it just came out in API level 8 aka version 2.2).

如果您正在使用一个较旧的SDK库(因为您想让它在使用较旧OS版本的手机上工作),那么就不会打包Base64类(因为它刚刚出现在API级别8,即2.2版本中)。

Check this article out for a work-around:

看看这篇文章,你会发现:

http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html

http://androidcodemonkey.blogspot.com/2010/03/how-to-base64-encode-decode-android.html

#2


85  

Instead of using Bitmap, you can also do this through trivial InputStream. Well I am not sure, but I think its a bit efficient

除了使用位图,您还可以通过普通的InputStream来实现这一点。我不确定,但我认为这有点有效率

InputStream inputStream = new FileInputStream(fileName);//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
    while ((bytesRead = inputStream.read(buffer)) != -1) {
    output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
String encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);

#3


6  

If you need base64 over JSON, check out Jackson: it has explicit support for binary data read/write as base64 at both low level (JsonParser, JsonGenerator) and data-binding level. So you can just have POJOs with byte[] properties, and encoding/decoding is automatically handled. And pretty efficiently too, should that matter.

如果需要base64而不是JSON,请查看Jackson:它在低级别(JsonParser, JsonGenerator)和数据绑定级别上都明确支持二进制数据读/写作为base64。因此,您可以使用带有byte[]属性的pojo,并自动处理编码/解码。而且效率也很高。

#4


3  

this code prefect run in my project

这段代码在我的项目中运行

profile_image.buildDrawingCache();
                Bitmap bmap = profile_image.getDrawingCache();
                String encodedImageData =getEncoded64ImageStringFromBitmap(bmap);


public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    bitmap.compress(CompressFormat.JPEG, 70, stream);
    byte[] byteFormat = stream.toByteArray();
    // get the base 64 string
    String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);

    return imgString;
}

#5


3  

// put the image file path into this method
  public static String getFileToByte(String filePath){
      Bitmap bmp = null;
      ByteArrayOutputStream bos = null;
      byte[] bt = null;
      String encodeString = null;
       try{
        bmp = BitmapFactory.decodeFile(filePath);
        bos = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos); 
        bt = bos.toByteArray();
        encodeString = Base64.encodeToString(bt, Base64.DEFAULT);
      }catch (Exception e){
        e.printStackTrace();
      }
      return encodeString;
}

#6


2  

If you're doing this on Android, here's a helper copied from the React Native codebase:

如果你在Android上做这个,这里有一个从React Native codebase复制的助手:

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import android.util.Base64;
import android.util.Base64OutputStream;
import android.util.Log;

// You probably don't want to do this with large files
// (will allocate a large string and can cause an OOM crash).
private String readFileAsBase64String(String path) {
  try {
    InputStream is = new FileInputStream(path);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    Base64OutputStream b64os = new Base64OutputStream(baos, Base64.DEFAULT);
    byte[] buffer = new byte[8192];
    int bytesRead;
    try {
      while ((bytesRead = is.read(buffer)) > -1) {
        b64os.write(buffer, 0, bytesRead);
      }
      return baos.toString();
    } catch (IOException e) {
      Log.e(TAG, "Cannot read file " + path, e);
      // Or throw if you prefer
      return "";
    } finally {
      closeQuietly(is);
      closeQuietly(b64os); // This also closes baos
    }
  } catch (FileNotFoundException e) {
    Log.e(TAG, "File not found " + path, e);
    // Or throw if you prefer
    return "";
  }
}

private static void closeQuietly(Closeable closeable) {
  try {
    closeable.close();
  } catch (IOException e) {
  }
}

#7


0  

byte[] decodedString = Base64.decode(result.getBytes(), Base64.DEFAULT);

#8


0  

Below are the pseudo code that may help you :

下面是伪代码,可以帮助您:

public  String getBase64FromFile(String path)
      { 
         Bitmap bmp = null; 
         ByteArrayOutputStream baos = null;  
         byte[] baat = null;
         String encodeString = null;  
         try
          {   
            bmp = BitmapFactory.decodeFile(path);     
            baos = new ByteArrayOutputStream();                 
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
            baat = baos.toByteArray(); 
            encodeString = Base64.encodeToString(baat, Base64.DEFAULT);
          }
          catch (Exception e)
          { 
           e.printStackTrace();  
          }  

        return encodeString;
     }

#9


-1  

Use this Code:

使用这段代码:

byte[ ] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);

Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);