android - 如何从 Android 将图像 blob 上传到 Azure

标签 android azure bitmap azure-storage azure-blob-storage

我很难将图像从 Android 设备上传到我的 Azure 云存储帐户。

下面是我已经开始工作的代码。但是,用户选择的图像返回一个 URI,并且我无法找到将 uri 转换为文件路径的解决方案(“工作”示例中硬编码的内容)。我在网上读到文件路径不再可接受,所以我尝试将照片转换为位图,并尝试使用涉及 getContextResolver() 的多种解决方案。但每次我尝试不同的策略时,都找不到文件或出现空指针异常。

//Code that works
final String filePath = "storage/emulated/0/DCIM/Camera/IMG_20190328_141613.jpg";
CloudBlockBlob blob = container.getBlockBlobReference(blobName);
File source = new File(filePath);
blob.upload(new FileInputStream(source), source.length());
//Alternative 1 that doesnt work
CloudBlockBlob blob = container.getBlockBlobReference(blobName);
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri,projection,null,null,null);
cursor.moveToFirst();
int colIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(colIndex);
cursor.close();
File source = new File(filePath);
blob.upload(new FileInputStream(source), source.length());

非常感谢有关此问题的任何帮助。

最佳答案

经过大量研究,我找到了迄今为​​止最好的解决方案。基本上我需要通过转换为位图来将我尝试从外部存储发送到内部的照片复制。完整解决方案如下。如果有人有更好的,请告诉我。

String connectionString = "{account key}";

CloudStorageAccount storageAccount = CloudStorageAccount.parse(connectionString);

// Create the blob client
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

// Get a reference to a container
// The container name must be lower case
CloudBlobContainer container = blobClient.getContainerReference({bucketName});

//Create new file
File f = new File(getApplicationContext().getCacheDir(), blobName);
f.createNewFile();

//Create byte array stream
ByteArrayOutputStream bos = new ByteArrayOutputStream();

/*bitmap is loaded in the onCreate method (not shown in this block) Quality is 0-100 where 100 is the best*/
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos);

byte[] bitmapdata = bos.toByteArray();

//write bitmap to file, flush and close.
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();

//upload bitmap from local directory
final String filePath = getApplicationContext().getCacheDir() + blobName;
CloudBlockBlob blob = container.getBlockBlobReference(blobName);
File source = new File(f.getAbsolutePath());
blob.upload(new FileInputStream(source), source.length());

关于android - 如何从 Android 将图像 blob 上传到 Azure,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55411172/

相关文章:

android - 图像尺寸加倍

android - 加载大图像

java - Android 按钮仅在第二次单击时启动方法

c# - 从 Azure Web App 托管服务标识创建资源组

azure - Azure 门户、开发人员门户和 Postman 之间的 APIM 响应 header 不同

azure - aspnetcore2.0 azure web应用程序部署启用组织身份验证

c# - 将 System.Drawing.Bitmap 转换为 WPF 的 System.Windows.Media.BitmapImage

Java 并发数 : synchronized statements/methods causing StackOverflowError exception

android - 从我的 Android 应用程序中调用 Adob​​e Reader

android - Twitter 日志记录和不重定向到应用程序以及如何使用回调 URL