【发布时间】: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();
}
}
}
convertImageToBytes 和 convertVideoToBytes 方法目前有效,但我只是想知道我是否正确执行此操作。
【问题讨论】:
-
你解码图像然后再次压缩它的原因是什么?
-
@harism 我不太确定——我认为是在 Stack Overflow 的回答中找到的。我对此真的没有什么经验,但这可能是因为您必须将图像路径转换为位图。
-
只是想知道,因为很可能不需要单独的图像和视频字节数组读取方法。
-
@harism 我确定是这样。
标签: android bytearray parse-platform binary-data