2017-02-17 99 views
0

我已经通过在线网站将图像转换为base64。 我通过这个link来保存一个String中的base64字符串。但我得到一个错误说 错误:(38,36)错误:字符串常量太长将base64字符串转换为Android中的图像

请让我知道如何为base64转换为图像(位图)Android中

+0

显示您的代码 –

回答

2
 //encode image(from image path) to base64 string 
       ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
       Bitmap bitmap = BitmapFactory.decodeFile(pathOfYourImage); 
       bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
       byte[] imageBytes = baos.toByteArray(); 
       String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT); 

    //encode image(image from drawable) to base64 string 
       ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
       Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.yourDrawableImage); 
       bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
       byte[] imageBytes = baos.toByteArray(); 
       String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT); 
1

你尝试使用类的BitmapFactory?

请尝试是这样的:

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT); 
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

另外,根据你的错误,看来你使用一个静态最终字符串来保存你base64编码字符串。在Java中,常量字符串的长度限制为64k。

1

首先检查你的字符串

http://codebeautify.org/base64-to-image-converter

试试这个方法来转换。

public class MainActivity extends AppCompatActivity { 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     ImageView image =(ImageView)findViewById(R.id.image); 

     //encode image to base64 string 
     ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.logo); 
     bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos); 
     byte[] imageBytes = baos.toByteArray(); 
     String imageString = Base64.encodeToString(imageBytes, Base64.DEFAULT); 

     //decode base64 string to image 
     imageBytes = Base64.decode(imageString, Base64.DEFAULT); 
     Bitmap decodedImage = BitmapFactory.decodeByteArray(imageBytes, 0, imageBytes.length); 
     image.setImageBitmap(decodedImage); 
    } 
} 

http://www.thecrazyprogrammer.com/2016/10/android-convert-image-base64-string-base64-string-image.html

2

您可以使用一些其他的内置方法基本上只是恢复你的代码。

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

Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 
相关问题