首页 > 移动平台 > 详细

Android SharedPreferences存图片,转码解码图片

时间:2015-03-25 16:50:59      阅读:426      评论:0      收藏:0      [点我收藏+]

保存图片  首先创建ByteArrayStream对象,然后用BitmapFactroy把图片加载进来,然后compress压缩图片到流,  然后toByteArray()就行了

 

 

public void disposeImage() 
    { 
        ByteArrayOutputStream outputStream = null; 
        try 
        { 
            SharedPreferences preferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Activity.MODE_PRIVATE); 
            Editor editor = preferences.edit(); 
            outputStream = new ByteArrayOutputStream(); 
            /* 
             * 读取和压缩图片资源  并将其保存在 ByteArrayOutputStream对象中 
             */ 
            BitmapFactory.decodeResource(getResources(), R.drawable.jt6).compress(CompressFormat.JPEG, 50, outputStream); 
            String imgBase64 = new String(Base64.encode(outputStream.toByteArray(), Base64.DEFAULT)); 
            editor.putString("image", imgBase64); 
            editor.commit(); 
            
            readImage(); 
        } 
        catch (Exception e) 
        { 
            e.printStackTrace(); 
        } 
        finally 
        { 
            if (null != outputStream) 
            { 
                try 
                { 
                    outputStream.close(); 
                } 
                catch (IOException e) 
                { 
                    e.printStackTrace(); 
                } 
            } 
        } 
    } 

    public void readImage() 
    { 
        ByteArrayInputStream inputStream = null; 
        try 
        { 
            SharedPreferences preferences = getSharedPreferences(SHARED_PREFERENCES_NAME, Activity.MODE_PRIVATE); 
            String imgbase64 = preferences.getString("image", ""); 
            byte[] imgbyte = Base64.decode(imgbase64.getBytes(), Base64.DEFAULT); 
            inputStream = new ByteArrayInputStream(imgbyte); 
            ImageView view = (ImageView) findViewById(R.id.preference_image); 
            view.setImageDrawable(Drawable.createFromStream(inputStream, "image")); 
        } 
        catch (Exception e) 
        { 
            e.printStackTrace(); 
        } 
        finally 
        { 
            if (null != inputStream) 
            { 
                try 
                { 
                    inputStream.close(); 
                } 
                catch (IOException e) 
                { 
                    e.printStackTrace(); 
                } 
            } 
        } 
    }

Android SharedPreferences存图片,转码解码图片

原文:http://www.cnblogs.com/wikiki/p/4365777.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!