本文主要是介绍图片和base64 String互转,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
在转换之前把要转的图片放在assets目录下
图片转base64 String
public String PicToString(String name){InputStream myInput = null;String string=null;try {myInput = MainActivity.this.getAssets().open(name);Bitmap bitmap = BitmapFactory.decodeStream(myInput);ByteArrayOutputStream bStream = new ByteArrayOutputStream();bitmap.compress(Bitmap.CompressFormat.PNG, 50, bStream);byte[] bytes = bStream.toByteArray();string = Base64.encodeToString(bytes, Base64.DEFAULT);Log.i("--------->", "转string成功");} catch (IOException e) {Log.i("--------->", "转string失败");}return string;}
这里写代码片
base64 String 转 bitmap
public Bitmap stringToBitmap(String string) {// 将字符串转换成Bitmap类型Bitmap bitmap = null;try {byte[] bitmapArray;bitmapArray = Base64.decode(string, Base64.DEFAULT);bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,bitmapArray.length);Log.i("--------->", "转bitmap成功");} catch (Exception e) {Log.i("--------->", "转bitmap失败");}return bitmap;}
这篇关于图片和base64 String互转的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!