繁体   English   中英

在 Android 设备上转换和保存图像文件时出现 NullPointerException

[英]NullPointerException when convert and save Image file on Android device

我正在尝试将图像类型数据作为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

有什么我错过或做错了吗?

原来图像文件必须重新组织,而对于 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();
                }

我还旋转了图片,以便在移动设备上更容易查看

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM