保存和retreving在解析照片和视频(安卓)照片、视频、retreving

2023-09-06 15:03:46 作者:将月色拉长

我一直在寻找在解析Android的文档,看到保存的照片和视频,你必须初始化新ParseFile 的名称和一个byte [数据]并保存。

I was looking at the Parse Android docs and saw that to save photos and videos, you have to initialize a new ParseFile with a name and a byte[] of data and save it.

什么是一个开放的图像和视频乌里转换为字节数组的最简单的方法?

下面是我尝试的解决方案:

Here are my attempted solutions:

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 方法现在的工作,但我只是想知道如果我干嘛干嘛这个正确的。

The convertImageToBytes and convertVideoToBytes methods work for now, but I'm just wondering If I'm doing doing this correctly.

推荐答案

从乌里得到的byte []我做以下事情,

From Uri to get byte[] I do the following things,

 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.