将原始Android图像转换为png

时间:2014-06-09 11:26:06

标签: android png screenshot

在有根的Android设备上,我想截取屏幕截图并将原始格式图像转换为Png图像,然后将其保存在本地。到目前为止,我设法访问帧缓冲区,截取屏幕截图并保存原始图像。问题是当我将其转换为Png格式时,我得到的图像都是错误的......一堆白色和灰色的线条。 这就是我所做的:

public void putRawImageInArray (byte [] array, File f ) throws IOException{
    @SuppressWarnings("resource")

    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(f));   //The framebuffer raw image is in the file
    bufferedInputStream.read(array, 0, array.length);//read the file
} 

public void convertToBitmap (byte [] rawarray) throws IOException{
            byte [] Bits = new byte[rawarray.length*4]; 
            int i;
            for(i=0;i<rawarray.length;i++)
            {
                Bits[i*4] =
                    Bits[i*4+1] =
                    Bits[i*4+2] = (byte) ~rawarray[i]; 
                Bits[i*4+3] = -1;//0xff, that's the alpha.
            }


            Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
            bm.copyPixelsFromBuffer(ByteBuffer.wrap(Bits)); 

            File f = new File(Environment.getExternalStorageDirectory(), "/pictures/picture.png");
            f.createNewFile();
            if (f.exists() == true) {
                f.delete();
            }
try{
            OutputStream fos=new FileOutputStream(f);
            bm.compress(CompressFormat.PNG, 100, fos);
            fos.close();
} catch (FileNotFoundException e) {
    Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
    Log.d(TAG, "Error accessing file: " + e.getMessage());
} 

我做错了什么?

1 个答案:

答案 0 :(得分:0)

尝试删除所有这些

    byte [] Bits = new byte[rawarray.length*4]; 
    int i;
    for(i=0;i<rawarray.length;i++)
    {
        Bits[i*4] =
            Bits[i*4+1] =
            Bits[i*4+2] = (byte) ~rawarray[i]; 
        Bits[i*4+3] = -1;//0xff, that's the alpha.
    }

直接使用rawarray

 Bitmap bm = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
 bm.copyPixelsFromBuffer(ByteBuffer.wrap(rawarray));

并确保您使用的颜色模型(Bitmap.Config.ARGB_8888)与图像数据的颜色模型相同。