Изменение размера изображения на сервере с последующей загрузкой в ​​Azure

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

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

public string UploadToCloud (FileUpload fup, string containerName) {// Получить учетную запись хранения из строки подключения. 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;
        }

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

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


person Simon    schedule 16.02.2013    source источник


Ответы (2)


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

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

    /// <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;
    }
person t00thy    schedule 20.03.2015

Я выполняю операцию изменения размера в приложении для 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% качества исходного изображения.

Надеюсь это поможет

person Luis Delgado    schedule 17.12.2013