将Bitmap对象上载到Azure blob存储

时间:2016-01-23 11:57:53

标签: c# azure azure-storage-blobs

我尝试下载,调整大小,然后将图片上传到Azure blob存储。

我可以下载原始图片并调整大小如下:

private bool DownloadandResizeImage(string originalLocation, string filename)
    {
        try
        {
            byte[] img;
            var request = (HttpWebRequest)WebRequest.Create(originalLocation);

            using (var response = request.GetResponse())
            using (var reader = new BinaryReader(response.GetResponseStream()))
            {
                img = reader.ReadBytes(200000);
            }

            Image original;

            using (var ms = new MemoryStream(img))
            {
                original = Image.FromStream(ms);
            }

            const int newHeight = 84;
            var newWidth = ScaleWidth(original.Height, 84, original.Width);

            using (var newPic = new Bitmap(newWidth, newHeight))
            using (var gr = Graphics.FromImage(newPic))
            {
                gr.DrawImage(original, 0, 0, newWidth, newHeight);
                // This is where I save the file, I would like to instead
                // upload it to Azure
                newPic.Save(filename, ImageFormat.Jpeg);


            }

            return true;
        }
        catch (Exception e)
        {
            return false;
        }

    }

我知道我可以使用UploadFromFile上传保存的文件,但是想知道是否有办法直接从我的对象进行,所以我不必先保存它?我已经尝试从流上传,并且可以在使用ms函数后执行此操作,但随后我调整了文件大小

2 个答案:

答案 0 :(得分:4)

为了完成Crowcoder在整个问题的上下文中的回答,我认为你需要的是:

// Retrieve storage account from connection string.
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_blobcnxn);
// Create the blob client.
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve a reference to a container.
CloudBlobContainer container = blobClient.GetContainerReference(containerName);

using (MemoryStream memoryStream = new MemoryStream())
{
    newPic.Save(memoryStream, ImageFormat.Jpeg);
    memoryStream.Seek(0, SeekOrigin.Begin); // otherwise you'll get zero byte files
    CloudBlockBlob blockBlob = jpegContainer.GetBlockBlobReference(filename);
    blockBlob.UploadFromStream(memoryStream);
}

答案 1 :(得分:2)

以上示例将您拥有的blob上传为Stream。它使用Azure客户端SDK:

private async Task WriteBlob(Stream blob, string containerName, string blobPath)
{
    // Retrieve storage account from connection string.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(_blobcnxn);

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

    // Retrieve a reference to a container.
    CloudBlobContainer container = blobClient.GetContainerReference(containerName);
    // Create the container if it doesn't already exist.
    await container.CreateIfNotExistsAsync();

    // create a blob in the path of the <container>/email/guid
    CloudBlockBlob blockBlob = container.GetBlockBlobReference(blobPath);

    await blockBlob.UploadFromStreamAsync(blob);
}
相关问题