【问题标题】:Saving and retreving photos and videos in Parse (Android)在 Parse (Android) 中保存和检索照片和视频
【发布时间】:2014-06-06 01:31:03
【问题描述】:

我在查看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 方法目前有效,但我只是想知道我是否正确执行此操作。

【问题讨论】:

  • 你解码图像然后再次压缩它的原因是什么?
  • @harism 我不太确定——我认为是在 Stack Overflow 的回答中找到的。我对此真的没有什么经验,但这可能是因为您必须将图像路径转换为位图。
  • 只是想知道,因为很可能不需要单独的图像和视频字节数组读取方法。
  • @harism 我确定是这样。

标签: android bytearray parse-platform binary-data


【解决方案1】:

从 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.

【讨论】:

  • 在将视频文件转换为字节数组时是否有可能减小视频文件的大小?请回复:(
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-05-31
  • 1970-01-01
  • 2012-12-18
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多