我使用这个(下面)代码从SD卡上的图片创建了一个base64字符串,它可以正常工作,但是当我尝试解码它时(甚至在下面),我得到了一个java.lang.outOfMemoryException,大概是因为我没有把字符串分成合理的在我编码之前,我在解码之前的大小.
byte fileContent[] = new byte[3000];
StringBuilder b = new StringBuilder();
try{
FileInputStream fin = new FileInputStream(sel);
while(fin.read(fileContent) >= 0) {
b.append(Base64.encodeToString(fileContent, Base64.DEFAULT));
}
}catch(IOException e){
}
Run Code Online (Sandbox Code Playgroud)
上面的代码效果很好,但是当我尝试使用以下代码解码图像时出现问题;
byte[] imageAsBytes = Base64.decode(img.getBytes(), Base64.DEFAULT);
ImageView image = (ImageView)this.findViewById(R.id.ImageView);
image.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
);
Run Code Online (Sandbox Code Playgroud)
我也试过这种方式
byte[] b = Base64.decode(img, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
image.setImageBitmap(bitmap);
Run Code Online (Sandbox Code Playgroud)
现在我假设我需要将字符串拆分成像我的图像编码代码一样的部分,但我不知道如何去做.
Pra*_*abu 13
您需要在像AsyncTask这样的后台线程中解码图像,或者您需要使用BitmapFactory降低图像质量.例:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inPurgeable=true;
Bitmap bm = BitmapFactory.decodeFile("Your image exact loaction",options);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
Run Code Online (Sandbox Code Playgroud)