android中Bitmap(图片)和String类型直接的转换

本文介绍如何在Android中进行Bitmap与String类型的相互转换,并探讨等比例缩放图片的方法,以适应ImageView显示。同时,分享了Java中关于File类的文件管理、读写操作以及图片下载的相关学习笔记链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

    /** * 图片转成string *  * @param bitmap * @return */ 
    public static String convertIconToString(Bitmap bitmap) { 
        ByteArrayOutputStream baos = new ByteArrayOutputStream();// outputstream 
        bitmap.compress(CompressFormat.PNG, 100, baos); 
        byte[] appicon = baos.toByteArray();// 转为byte数组
        return Base64.encodeToString(appicon, Base64.DEFAULT); 
     } 


    /** * string转成bitmap *  * @param st */
     public static Bitmap convertStringToIcon(String st) { 
        // OutputStream out; 
        Bitmap bitmap = null;
         try {
             // out = new FileOutputStream("/sdcard/aa.jpg");
             byte[] bitmapArray; 
            bitmapArray = Base64.decode(st, Base64.DEFAULT); 
            bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0, bitmapArray.length); 
            // bitmap.compress(Bitmap.CompressFormat.PNG, 100, out); 
            return bitmap; 
        } catch (Exception e) { return null; } }

从preference中去除图片填充到ImageView中

Bitmap photo=convertStringToIcon(preferences.getString("photo", "无法获取"));//将图片从String类型转换成Bitmap
            Drawable drawable = new BitmapDrawable(photo);
            dt_info_head_photo.setImageDrawable(drawable);

等比例缩放图片

   public static Bitmap zoomImg(Bitmap bm, int newWidth ,int newHeight){
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        ELog.e("====newbm====="+newbm.getHeight());
        return newbm;
    }

Java学习笔记——File类之文件管理和读写操作、下载图片(借鉴学习参考文章)
http://blog.youkuaiyun.com/jueblog/article/details/9429953

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值