我已經通過在線網站將圖像轉換爲base64。 我通過這個link來保存一個String中的base64字符串。但我得到一個錯誤說 錯誤:(38,36)錯誤:字符串常量太長將base64字符串轉換爲Android中的圖像
請讓我知道如何爲base64轉換爲圖像(位圖)Android中
我已經通過在線網站將圖像轉換爲base64。 我通過這個link來保存一個String中的base64字符串。但我得到一個錯誤說 錯誤:(38,36)錯誤:字符串常量太長將base64字符串轉換爲Android中的圖像
請讓我知道如何爲base64轉換爲圖像(位圖)Android中
//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);
你嘗試使用類的BitmapFactory?
請嘗試是這樣的:
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
另外,根據你的錯誤,看來你使用一個靜態最終字符串來保存你base64編碼字符串。在Java中,常量字符串的長度限制爲64k。
首先檢查你的字符串
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);
}
}
您可以使用一些其他的內置方法基本上只是恢復你的代碼。
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
顯示您的代碼 –