在Parse(Android)中保存和检索照片和视频

时间:2014-06-06 01:31:03

标签: android bytearray parse-platform binary-data

我正在查看Parse Android docs并看到要保存照片和视频,您必须使用名称和字节[]数据初始化new ParseFile并保存。

将图像Uri和视频Uri转换为字节数组的最简单方法是什么?

以下是我尝试过的解决方案:

mPhoto = new ParseFile("img", convertImageToBytes(Uri.parse(mPhotoUri)));
mVideo = new ParseFile ("vid", convertVideoToBytes(Uri.parse(mVideoUri)));

private byte[] convertImageToBytes(Uri uri){
    byte[] data = null;
    try {
        ContentResolver cr = getBaseContext().getContentResolver();
        InputStream inputStream = cr.openInputStream(uri);
        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        data = baos.toByteArray();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    return data;
}

private byte[] convertVideoToBytes(Uri uri){
    byte[] videoBytes = null;
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        FileInputStream fis = new FileInputStream(new File(getRealPathFromURI(this, uri)));

        byte[] buf = new byte[1024];
        int n;
        while (-1 != (n = fis.read(buf)))
            baos.write(buf, 0, n);

        videoBytes = baos.toByteArray();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return videoBytes;
}

private String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Video.Media.DATA };
        cursor = context.getContentResolver().query(contentUri, proj, null,
                null, null);
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}    

convertImageToBytesconvertVideoToBytes方法现在可以使用,但我只是想知道我是否正确地执行此操作。

1 个答案:

答案 0 :(得分:7)

从Uri获取byte []我会做以下事情,

 ByteArrayOutputStream baos = new ByteArrayOutputStream();
FileInputStream fis = new FileInputStream(new File(yourUri));

byte[] buf = new byte[1024];
int n;
while (-1 != (n = fis.read(buf)))
    baos.write(buf, 0, n);

byte[] videoBytes = baos.toByteArray(); //this is the video in bytes.