2013-02-16 3 views
3

У меня есть следующая функция, которую я использую для загрузки файлов на лазурный учет.Изменение размера изображения на сервере, а затем загрузка на azure

Как вы увидите, что он не делает вида изменения размера и т.д.:

общественных струнного UploadToCloud (FileUpload FUP, строка ИмяКонтейнера) { // Получает счет хранения из строки подключения. CloudStorageAccount storageAccount = CloudStorageAccount.Parse (ConfigurationManager.AppSettings ["StorageConnectionString"]);

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

    // Retrieve a reference to a container. 
    CloudBlobContainer container = blobClient.GetContainerReference(containerName); 

    string newName = ""; 
    string ext = ""; 
    CloudBlockBlob blob = null; 


    // Create the container if it doesn't already exist. 
    container.CreateIfNotExists(); 

    newName = ""; 
    ext = Path.GetExtension(fup.FileName); 

    newName = string.Concat(Guid.NewGuid(), ext); 

    blob = container.GetBlockBlobReference(newName); 

    blob.Properties.ContentType = fup.PostedFile.ContentType; 

    //S5: Upload the File as ByteArray    
    blob.UploadFromStream(fup.FileContent); 

    return newName; 


} 

Я тогда эта функция, которую я использовал на сайтах не размещается на лазури:

public string ResizeandSave(FileUpload fileUpload, int width, int height, bool deleteOriginal, string tempPath = @"~\tempimages\", string destPath = @"~\cmsgraphics\") 
     { 
      fileUpload.SaveAs(Server.MapPath(tempPath) + fileUpload.FileName); 

      var fileExt = Path.GetExtension(fileUpload.FileName); 
      var newFileName = Guid.NewGuid().ToString() + fileExt; 

      var imageUrlRS = Server.MapPath(destPath) + newFileName; 

      var i = new ImageResizer.ImageJob(Server.MapPath(tempPath) + fileUpload.FileName, imageUrlRS, new ImageResizer.ResizeSettings(
          "width=" + width + ";height=" + height + ";format=jpg;quality=80;mode=max")); 

      i.CreateParentDirectory = true; //Auto-create the uploads directory. 
      i.Build(); 

      if (deleteOriginal) 
      { 
       var theFile = new FileInfo(Server.MapPath(tempPath) + fileUpload.FileName); 

       if (theFile.Exists) 
       { 
        File.Delete(Server.MapPath(tempPath) + fileUpload.FileName); 
       } 
      } 

      return newFileName; 
     } 

Теперь то, что я пытаюсь сделать, это попытаться объединить два ... или, по крайней мере, работа вы можете изменить размер изображения, прежде чем хранить его на лазури.

У кого-нибудь есть идеи?

ответ

0

Я делаю операцию изменения размера на приложении Windows Phone 8. Поскольку вы можете представить, что время выполнения для WP8 намного ограничено по сравнению со всей средой выполнения .NET, поэтому могут быть другие варианты, чтобы сделать это более эффективно, если у вас нет тех же ограничений, что и я.

public static void ResizeImageToUpload(Stream imageStream, PhotoResult e) 
    {    
     int fixedImageWidthInPixels = 1024; 
     int verticalRatio = 1; 

     BitmapImage bitmap = new BitmapImage(); 
     bitmap.SetSource(e.ChosenPhoto); 
     WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap); 
     if (bitmap.PixelWidth > fixedImageWidthInPixels) 
      verticalRatio = bitmap.PixelWidth/fixedImageWidthInPixels; 
     writeableBitmap.SaveJpeg(imageStream, fixedImageWidthInPixels, 
      bitmap.PixelHeight/verticalRatio, 0, 80);          
    } 

Код будет изменять размер изображения, если его ширина больше 1024 пикселей. Переменная verticalRatio используется для вычисления пропорции изображения, чтобы не потерять его соотношение сторон во время изменения размера. Затем код кодирует новый jpeg, используя 80% качества исходного изображения.

Надеется, что это помогает

1

Я надеюсь, что вы уже сделать его работу, но я искал какой-то рабочий раствор сегодня, любой я не могу найти его. Но, наконец, я сделал это.

Вот мой код, надеюсь, что это поможет кому-то:

/// <summary> 
    /// Saving file to AzureStorage 
    /// </summary> 
    /// <param name="containerName">BLOB container name</param> 
    /// <param name="MyFile">HttpPostedFile</param> 
    public static string SaveFile(string containerName, HttpPostedFile MyFile, bool resize, int newWidth, int newHeight) 
    { 
     string fileName = string.Empty; 

     try 
     { 
      CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.ConnectionStrings["StorageConnectionString"].ConnectionString); 
      CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient(); 
      CloudBlobContainer container = blobClient.GetContainerReference(containerName); 
      container.CreateIfNotExists(BlobContainerPublicAccessType.Container); 

      string timestamp = Helper.GetTimestamp() + "_"; 
      string fileExtension = System.IO.Path.GetExtension(MyFile.FileName).ToLower(); 
      fileName = timestamp + MyFile.FileName; 

      CloudBlockBlob blockBlob = container.GetBlockBlobReference(fileName); 
      blockBlob.Properties.ContentType = MimeTypeMap.GetMimeType(fileExtension); 

      if (resize) 
      { 
       Bitmap bitmap = new Bitmap(MyFile.InputStream); 

       int oldWidth = bitmap.Width; 
       int oldHeight = bitmap.Height; 

       GraphicsUnit units = System.Drawing.GraphicsUnit.Pixel; 
       RectangleF r = bitmap.GetBounds(ref units); 
       Size newSize = new Size(); 

       float expectedWidth = r.Width; 
       float expectedHeight = r.Height; 
       float dimesion = r.Width/r.Height; 

       if (newWidth < r.Width) 
       { 
        expectedWidth= newWidth; 
        expectedHeight = expectedWidth/ dimesion; 
       } 
       else if (newHeight < r.Height) 
       { 
        expectedHeight = newHeight; 
        expectedWidth= dimesion * expectedHeight; 
       } 
       if (expectedWidth> newWidth) 
       { 
        expectedWidth= newWidth; 
        expectedHeight = expectedHeight/expectedWidth; 
       } 
       else if (nPozadovanaVyska > newHeight) 
       { 
        expectedHeight = newHeight; 
        expectedWidth= dimesion* expectedHeight; 
       } 
       newSize.Width = (int)Math.Round(expectedWidth); 
       newSize.Height = (int)Math.Round(expectedHeight); 

       Bitmap b = new Bitmap(bitmap, newSize); 

       Image img = (Image)b; 
       byte[] data = ImageToByte(img); 

       blockBlob.UploadFromByteArray(data, 0, data.Length); 
      } 
      else 
      { 
       blockBlob.UploadFromStream(MyFile.InputStream); 
      }     
     } 
     catch 
     { 
      fileName = string.Empty; 
     } 

     return fileName; 
    } 

    /// <summary> 
    /// Image to byte 
    /// </summary> 
    /// <param name="img">Image</param> 
    /// <returns>byte array</returns> 
    public static byte[] ImageToByte(Image img) 
    { 
     byte[] byteArray = new byte[0]; 
     using (MemoryStream stream = new MemoryStream()) 
     { 
      img.Save(stream, System.Drawing.Imaging.ImageFormat.Png); 
      stream.Close(); 

      byteArray = stream.ToArray(); 
     } 
     return byteArray; 
    }