none
Compresser une image RRS feed

  • Question

  • Bonjour!

    je suis en train de développer un site web et je voudrai savoir comment gérer la compression  automatique des images coté client ou server  ex( 2 Mo à 300 ko ) lorsque le client charge l'image sur le site.

    Un exemple de code sera la bien venu.

    Merci

    mercredi 30 mars 2016 07:18

Réponses

  • Un exemple ci-dessous d'une classe que j'ai faite qui resize toutes les images d'un dossier et les sauvegarde dans un autre. A vous de l'adapter :

        public class ResizerService
        {
            
            public void ResizeFolder(string sourceFolder, string destinationFolder, int maxWidth, int maxHeight)
            {
                Parallel.ForEach(Directory.GetFiles(sourceFolder, "*.jpg"), fileName =>
                {
                    var bmp = new Bitmap(fileName);
                    var exif = new EXIFextractor(ref bmp, "n"); // get source from http://www.codeproject.com/KB/graphics/exifextractor.aspx?fid=207371
    
                    var originalOrientation = OrientationToFlipType(exif["Orientation"]?.ToString());
    
                    var destFileName = Path.Combine(destinationFolder, Path.GetFileName(fileName));
                    Resize(fileName, destFileName, maxWidth, maxHeight);
    
                    if (originalOrientation != RotateFlipType.RotateNoneFlipNone)
                    {
                        bmp = new Bitmap(destFileName);
                        bmp.RotateFlip(originalOrientation);
                        bmp.Save(destFileName, ImageFormat.Jpeg);
                    }
                });
            }
    
            public void Resize(string sourceFileName, string destinationFileName, int maxWidth, int maxHeight)
            {
                var baSource = File.ReadAllBytes(sourceFileName);
                using (Stream mem = new MemoryStream(baSource))
                {
                    var bmpFrame = ReadBitmapFrame(mem);
    
                    // To preserve the aspect ratio
                    var ratioX = maxWidth / (1d * bmpFrame.PixelWidth);
                    var ratioY = maxHeight / (1d * bmpFrame.PixelHeight);
                    var ratio = Math.Min(ratioX, ratioY);
    
                    // New width and height based on aspect ratio
                    var newWidth = (int)(bmpFrame.PixelWidth * ratio);
                    var newHeight = (int)(bmpFrame.PixelHeight * ratio);
    
    
                    var newBmpFrame = FastResize(bmpFrame, newWidth, newHeight);
                    var bmpResized = JpgToByteArray(newBmpFrame);
    
                    File.WriteAllBytes(destinationFileName, bmpResized);
                }
    
            }
            private static BitmapFrame FastResize(BitmapSource bmpSource, int newWidth, int newHeight)
            {
                var bmp = new TransformedBitmap(bmpSource, new ScaleTransform(newWidth / (1d * bmpSource.PixelWidth), (1d * newHeight / bmpSource.PixelHeight), 0, 0));
                return BitmapFrame.Create(bmp);
            }
    
            private static byte[] PngToByteArray(BitmapFrame bfResize)
            {
                using (var msStream = new MemoryStream())
                {
                    var pbdDecoder = new PngBitmapEncoder();
                    pbdDecoder.Frames.Add(bfResize);
                    pbdDecoder.Save(msStream);
                    return msStream.ToArray();
                }
            }
    
            private static byte[] JpgToByteArray(BitmapFrame bfResize)
            {
                using (var mem = new MemoryStream())
                {
                    var encoder = new JpegBitmapEncoder {QualityLevel = 50};
                    encoder.Frames.Add(bfResize);
                    encoder.Save(mem);
                    return mem.ToArray();
                }
            }
    
            private static BitmapFrame ReadBitmapFrame(Stream streamPhoto)
            {
                var bdDecoder = BitmapDecoder.Create(streamPhoto, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
                return bdDecoder.Frames[0];
            }
    
            private static RotateFlipType OrientationToFlipType(string orientation)
            {
                if (orientation == null)
                    return RotateFlipType.RotateNoneFlipNone;
    
                switch (int.Parse(orientation))
                {
                    case 1:
                        return RotateFlipType.RotateNoneFlipNone;
                    case 2:
                        return RotateFlipType.RotateNoneFlipX;
                    case 3:
                        return RotateFlipType.Rotate180FlipNone;
                    case 4:
                        return RotateFlipType.Rotate180FlipX;
                    case 5:
                        return RotateFlipType.Rotate90FlipX;
                    case 6:
                        return RotateFlipType.Rotate90FlipNone;
                    case 7:
                        return RotateFlipType.Rotate270FlipX;
                    case 8:
                        return RotateFlipType.Rotate270FlipNone;
                    default:
                        return RotateFlipType.RotateNoneFlipNone;
                }
            }


    Richard Clark
    Consultant - Formateur .NET
    http://www.c2i.fr
    Depuis 1996: le 1er site .NET francophone

    mercredi 30 mars 2016 13:08