2016-04-28 77 views
0

我正在从位图格式的图库中读取图像。将它保存到数据库时,我需要将它转换为字节,而在Image Adapter类中,我需要将它转换为位图。将位图转换为字节,反之亦然

以下是代码: - 转换为字节,以便它

public void submitAction(View view) 
    { 
     /*This method creates a new post and populates it with the data added by the user. The data is then stored in the database 
     * using the Active Android Library.*/ 
     Post p = new Post(); 
     EditText title = (EditText) findViewById(R.id.post_title_input); 
     String tit = title.getText().toString(); 
     EditText description = (EditText)findViewById((R.id.editText)); 
     String desc = description.getText().toString(); 
     Bitmap img = yourSelectedImage; 
     p.title=tit; 
     p.description=desc; 
     p.section="science"; 
     int bytes = img.getByteCount(); 
     ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer 
     img.copyPixelsToBuffer(buffer); 
     byte[] array = buffer.array(); 

    } 

代码存储在数据库中imageAdapter类 - 转换字节[]为位图

public View getView(int position, View convertView, ViewGroup parent) { 
     ImageView imageView; 
     if (convertView == null) { 
      // if it's not recycled, initialize some attributes 
      imageView = new ImageView(mContext); 
      imageView.setLayoutParams(new GridView.LayoutParams(85, 85)); 
      imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); 
      imageView.setPadding(8, 8, 8, 8); 
     } else { 
      imageView = (ImageView) convertView; 
     } 

     /*Converting image to byte*/ 
     Post p = posts.get(position); 
     byte[] image = p.image; 
     ByteArrayInputStream imageStream = new ByteArrayInputStream(image); 
     Bitmap theImage = BitmapFactory.decodeStream(imageStream); 
     imageView.setImageBitmap(theImage); 
     return imageView; 
    } 

当捉迷藏的应用程序,它在第Bitmap theImage = BitmapFactory.decodeStream(imageStream);行崩溃并以空指针异常终止。

回答

1

位图为byte []

Bitmap bitmap = ...; 
ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream); 
byte[] byteArray = stream.toByteArray(); 

字节[]为位图

Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray , 0, byteArray.length); 
相关问题