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

Evo*_*net 4 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;
        }

    }
Run Code Online (Sandbox Code Playgroud)

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

Chr*_*Rae 5

只是为了在整个问题的背景下完成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);
}
Run Code Online (Sandbox Code Playgroud)