Android相机 - 如何从字节数组中获取特定的“矩形”?

时间:2012-03-11 15:41:57

标签: android camera crop photos

我创建了一个可以拍摄和保存照片的应用程序。 我在预览的顶部有预览和叠加。 叠加层定义了一个正方形(正方形周围的区域显示预览有点暗),如图所示:

example

我需要做的是提取图像中正方形所在的部分。 方块的定义如下:

    Rect frame = new Rect(350,50,450,150);

我该怎么做?我有可以保存的字节数组(byte []数据),但我想更改应用程序,以便只保存方形区域。

编辑:我尝试了以下内容:

int[] pixels = new int[100000];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data.length);
            bitmap.getPixels(pixels, 0, 480, 350, 50, 100, 100);
            bitmap = Bitmap.createBitmap(pixels, 0, 100, 100, 100, Config.ARGB_4444);
            bitmap.compress(CompressFormat.JPEG, 0, bos);
            byte[] square = bos.toByteArray();

然后将数组“square”写入新文件... 问题是我得到了一条由线组成的图片......我所做的转换存在问题

2 个答案:

答案 0 :(得分:10)

花了一些时间才弄清楚代码应该是这样的:

int[] pixels = new int[100*100];//the size of the array is the dimensions of the sub-photo
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        Bitmap bitmap = BitmapFactory.decodeByteArray(data , 0, data.length);
        bitmap.getPixels(pixels, 0, 100, 350, 50, 100, 100);//the stride value is (in my case) the width value
        bitmap = Bitmap.createBitmap(pixels, 0, 100, 100, 100, Config.ARGB_8888);//ARGB_8888 is a good quality configuration
        bitmap.compress(CompressFormat.JPEG, 100, bos);//100 is the best quality possibe
        byte[] square = bos.toByteArray();

答案 1 :(得分:4)

相机预览数据采用YUV格式(特别是ImageFormat.NV21),BitmapFactory不直接支持。您可以使用YuvImage将其转换为如here所述的位图。唯一的区别是你想要在调用YuvImage.compressToJpeg时传递一个对应于你想要的方格的Rect。