如何在Android Java应用程序中获取设备中的图像

11

我的应用程序需要上传图片。

为此,我需要从安卓设备的图库获取图片。

我该如何编写代码来完成这个任务?

1个回答

39

使用动作为ACTION_GET_CONTENT,类型为"image/*"的Intent,将会启动照片选择器Activity。当用户选择一张图片后,您可以使用onActivityResult回调来获取结果。

类似这样:

Intent photoPickerIntent = new Intent(Intent.ACTION_GET_CONTENT);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);

protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == RESULT_OK)
    {
        Uri chosenImageUri = data.getData();

        Bitmap mBitmap = null;
        mBitmap = Media.getBitmap(this.getContentResolver(), chosenImageUri);
        }
}

1
嗨,Samuh。使用这段代码,我可以从媒体中获取图像,但我的问题是我需要将该图像存储在远程服务器上。我已经将mBitmap转换为字节数组,但当我尝试发送字节数组时,它显示了一个5位数的代码,我感觉它是字节数组的地址。你能帮我解决这个问题吗?提前致谢,Aswan - Aswan
1
你可能正在发送字节数组的HashCode而不是数组元素。 - Samuh
1
in = new FileInputStream("/sdcard/pictures/einstein3.jpg"); buf = new BufferedInputStream(in,2000); System.out.println("1.................."+buf); byte[] byteArray= new byte[buf.available()]; buf.read(byteArray);现在我正在将“byteArray”发送到服务器,但它没有发送哈希码。你能告诉我我犯了什么错误吗? - Aswan
在Android 4.4上,这现在具有不希望的行为(启动最近文档屏幕)。请参见此答案:https://dev59.com/8nE95IYBdhLWcg3wAo5U#2507973 - Martin Konecny

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接