图片和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;
    }

你可能感兴趣的:(java,android,String,base64)