2016-01-23 137 views
1

我試圖下載,調整大小然後將圖像上傳到Azure blob存儲。將位圖對象上傳到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函數後執行此操作,但是隨後我調整文件大小

+0

'我嘗試了從流上傳'。你的嘗試在哪裏?無論如何,你的代碼有問題。在使用'original'之前,你不應該使用'ms'。 –

+0

在調整大小之前,我可以使用original.UploadFromStream(memoryStream),但這是在調整大小之前 – Evonet

+0

而不是將newPic保存到文件,然後將其上傳到blob存儲,則需要直接上載newPic。我的理解是否正確? –

回答

1

以下是上傳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); 
} 
+0

如此容易downvote是不是?猜猜我最好把這段代碼從生產中拿出來,因爲它一定很糟糕。 – Crowcoder

+0

我沒有投票,我真的覺得這很有幫助! – Evonet

+0

@Evonet,我不認爲這是你。很高興幫助! – Crowcoder

相關問題