将位图对象上传到 Azure blob 存储

Uploading a Bitmap object to Azure blob storage

我正在尝试下载、调整图像大小,然后将图像上传到 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 函数后执行此操作,但随后我调整了文件大小

这是一个上传您拥有的 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);
}

只是为了在整个问题的上下文中完成 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);
}