`
mickey_hou
  • 浏览: 238367 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

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

阅读更多
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();
                }
            }
        }
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics