• BitmapFactory.decodeByteArray() 返回null,分析与解决


    问题描述:用android自带的Camera获取图片,上传至远程数据库中(mysql),以BLOB格式存储,

    但在提取图片时,始终无法在android界面显示,示例代码如下:

       .....  ....

       s = new Socket("192.168.0.68", 9999);
       din = new DataInputStream(s.getInputStream());

       ...   ...

       int size = din.readInt();//读取服务器端传来的图片数据
       byte[] bs = new byte[size];
       din.read(bs);

       Bitmap b = BitmapFactory.decodeByteArray(bs,0,bs.length);
       

       Log.i("kkk00",String.valueOf(b));//输出测试,bitmap始终为NUll

    解决方法:

    方法1:增加转码处理

       int size = din.readInt();//读取服务器端传来的图片数据
       byte[] bs = new byte[size];
       din.read(bs);

       YuvImage yuvimage=new YuvImage(bs, ImageFormat.NV21, 20,20, null);//20、20分别是图的宽度与高度
           ByteArrayOutputStream baos = new ByteArrayOutputStream();
           yuvimage.compressToJpeg(new Rect(0, 0,20, 20), 80, baos);//80--JPG图片的质量[0-100],100最高
           byte[] jdata = baos.toByteArray();

           Bitmap bmp = BitmapFactory.decodeByteArray(jdata, 0, jdata.length);

    测试:bmp不为空,放入控件中可正常显示。

    方法2:当图片以二进制形式传至服务器端时,将其存储到本机上,在以文件流的形式存入mysql数据库中

         .......

         int size = din.readInt();//读取图片数组的长度
         FileOutputStream fos = new FileOutputStream("c:/bbbb1.bmp"); 
         int len=0;
         byte[] mm=new byte[1024];
         while(true) {
          int m=din.read(mm);
          len=len+m;
          fos.write(mm,0,m);
          if(len>=size) break; 
         }
         fos.close();

         

        //在读取文件写入mysql

        ..... ...

         File file = new File("c:/bbbb1.bmp");  
         int length = (int) file.length();   
        InputStream fin = new FileInputStream(file); 
        pstmt.setBinaryStream (9, fin, length);

  • 相关阅读:
    centos7
    aaa
    20199122 2019-2020-2 《网络攻防实践》第三周作业
    20189304李小涛网络攻防第二周作业
    20189304《网络攻防》第一周作业
    2019-2020-2 20199137 《网络攻防实践》第三次作业
    容器抓包方法
    打印输出10分钟日志内容
    linux shell 检查脚本参数
    Structure needs cleaning(结构需要清理)解决
  • 原文地址:https://www.cnblogs.com/exmyth/p/4773965.html
Copyright © 2020-2023  润新知