Byte存储为String时遇到的问题

做App时,每当节假日,公司都会要求更换启动图,如果不更改其它功能的话,再打包个APP发布到线上是完全多余的事情,想到可以利用数据存储流来处理图片,这里做个记录

//请求网络接口获取启动图,将图片转为流式
@Override
public void onSuccess(File result_img){
    byte [] mByte = getByte(result_img);
    //将得到的byte[]转为Sting并放入SharePreference里
    SharedPreferences sharedPreferences = getSharedPreferences("fileIO", MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        try {
        //ISO-8859-1为国际通用编码,用以正确的存储流
            editor.putString("dex_startImage", new String(mByte, "ISO-8859-1"));

            editor.commit();
            //这里我们进行取流操作
            sharedPreferences = getSharedPreferences("fileIO", MODE_PRIVATE);
            String fileIOString = sharedPreferences.getString("dex_startImage", "");
            byte[] asd_byte = fileIOString.getBytes("ISO-8859-1");

    //将byte转为bitmap再转为BitmapDrawable
            BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(), BitmapFactory.decodeByteArray(asd_byte, 0, asd_byte.length));

            (LinearLayout)findviewbyId(R.id.mainactivity_linearLayout).setBackground(bitmapDrawable);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
}

//图片文件转为流
public byte[] getBytes(File file) {
        byte[] buffer = null;
        try {
            File mFile = file;
            FileInputStream fis = new FileInputStream(mFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }





}

非常简单,值得注意的就是存取byte时要设置编码标准,不然默认String是无法全部识别byte的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值