nullpointerexception

zazmityj  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(299)

我正在尝试将一个图像类型的数据以jpg文件的形式保存到sd卡上,我计划首先将其转换为位图,将位图压缩为jpeg格式,然后使用fileoutputstream将其保存到sd卡上。
这是我的密码:

File imagefile = new File(sdCardPath, "image.jpg");
Image image = fromFrame.getImage();

ByteBuffer bbuffer = image.getPlanes()[0].getBuffer();
byte[] byts = new byte[bbuffer.capacity()];
bbuffer.get(byts);
Bitmap bitmapImage = BitmapFactory.decodeByteArray(byts, 0, byts.length, null);
try{
    FileOutputStream out = new FileOutputStream(imagefile);
    bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, out);
    out.flush();
    out.close();
} catch (FileNotFoundException e) {
    Log.v(TAG, "FileNotFoundExceptionError " + e.toString());
} catch (IOException e) {
    Log.v(TAG, "IOExceptionError " + e.toString());
}

它给出了错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'boolean 
android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat, 
int, java.io.OutputStream)' on a null object reference

我有什么遗漏或做错的吗?

uubf1zoe

uubf1zoe1#

结果是图像文件必须重新组织,对于depth16文件,每个像素都有16位数据,因此将其转换为jpg文件的代码是:

Image depthimage = fromFrame.getImage();
int imwidth = depthImage.getWidth();
int imheight = depthImage.getHeight();
Image.Plane plane = depthImage.getPlanes()[0];
ShortBuffer shortDepthBuffer = plane.getBuffer().asShortBuffer();
File sdCardFile = Environment.getExternalStorageDirectory();
File file = new File(sdCardFile, "depthImage.jpg");
Bitmap disBitmap = Bitmap.createBitmap(imwidth, imheight, Bitmap.Config.RGB_565);
    for (int i = 0; i < imheight; i++) {
        for (int j = 0; j < imwidth; j++) {
            int index = (i * imwidth + j) ;
            shortDepthBuffer.position(index);
            short depthSample = shortDepthBuffer.get();
            short depthRange = (short) (depthSample & 0x1FFF);
            byte value = (byte) depthRange ;
            disBitmap.setPixel(j, i, Color.rgb(value, value, value));
   }
}
            Matrix matrix = new Matrix();
            matrix.setRotate(90);
            Bitmap rotatedBitmap = Bitmap.createBitmap(disBitmap, 0, 0, imwidth, imheight, matrix, true);
            try {
                FileOutputStream out = new FileOutputStream(file);
                rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
                MainActivity.num++;
                } catch (Exception e) {
                e.printStackTrace();
                }
                } catch (Exception e) {
                e.printStackTrace();
                }

我还可以旋转图片,以便在移动设备上查看

相关问题