SetResolution() public method

public SetResolution ( float xDpi, float yDpi ) : void
xDpi float
yDpi float
return void
Exemplo n.º 1
14
 // This is to resize an image file biased to the width of the image
 public void ResizeImageProportionate_XInclination(Stream File_Stream, int Target_Width, string Save_Path)
 {
     try
     {
         // This to extract the image from the file stream without uploading
         System.Drawing.Image _image = System.Drawing.Image.FromStream(File_Stream);
         int Image_Width = _image.Width;
         int Image_Height = _image.Height;
         int target_width = Target_Width;
         int target_height = (Target_Width * Image_Height) / Image_Width;
         // This is to create a new image from the file stream to a specified height and width
         Bitmap _bitmap = new Bitmap(target_width, target_height, _image.PixelFormat);
         _bitmap.SetResolution(72, 72);
         // This is to resize the image to the target height and target width
         Graphics _graphics = Graphics.FromImage(_bitmap);
         _graphics.DrawImage(_image, new Rectangle(0, 0, target_width, target_height),
            new Rectangle(0, 0, Image_Width, Image_Height), GraphicsUnit.Pixel);
         // This is to save the image file into the save path
         _bitmap.Save(Save_Path, _image.RawFormat);
         _image.Dispose();
         _graphics.Dispose();
         _bitmap.Dispose();
     }
     catch (Exception e)
     {
         throw e;
     }
 }
Exemplo n.º 2
0
        /// <summary>
        /// Resizes the specified image to the specifed size.
        /// </summary>
        /// <param name="image">The image to resize.</param>
        /// <param name="width">The width in pixels of the resized image.</param>
        /// <param name="height">The height in pixels of the resized image.</param>
        /// <param name="dispose">The value indicating whether to dispose the specified image after returning the new resized bitmap.</param>
        /// <returns>The specifed image, resized to the specified size.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// Thrown when 'image' is null.
        /// </exception>
        /// <exception cref="System.ArgumentOutOfRangeException">
        /// Thrown when 'width' is less than 0.
        ///  - OR -
        /// Thrown when 'height' is less than 0.
        /// </exception>
        public static Bitmap ResizeImage(Image image, int width, int height, bool dispose = true)
        {
            // http://stackoverflow.com/questions/1922040/resize-an-image-c-sharp

            if (image == null)
                throw new ArgumentNullException(nameof(image));
            if (width < 0)
                throw new ArgumentOutOfRangeException(nameof(width), width, "'" + nameof(width) + "' cannot be less than 0.");
            if (height < 0)
                throw new ArgumentOutOfRangeException(nameof(height), height, "'" + nameof(height) + "' cannot be less than 0.");

            Bitmap bitmap = new Bitmap(width, height);
            Graphics graphics = Graphics.FromImage(bitmap);
            ImageAttributes attributes = new ImageAttributes();

            #region >> Sets settings for high quality resizing

            bitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution);
            graphics.CompositingMode = CompositingMode.SourceCopy;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
            attributes.SetWrapMode(WrapMode.TileFlipXY);

            #endregion
            graphics.DrawImage(image, new Rectangle(0, 0, width, height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);

            if (dispose) image.Dispose();
            graphics.Dispose();
            attributes.Dispose();

            return bitmap;
        }
        /// <summary>
        /// 主要作業方法
        /// </summary>
        public Image Operation()
        {
            int OriginalWidth = image.Width;
            int OriginalHeight = image.Height;

            if (OriginalHeight > OriginalWidth)
            {
                _width = (int)(OriginalWidth * ((float)_height / (float)OriginalHeight));
            }
            else
            {
                _height = (int)(OriginalHeight * ((float)_width / (float)OriginalWidth));
            }

            bmPhoto = new Bitmap(_width, _height, PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(72, 72);
            Graphics g = Graphics.FromImage(bmPhoto);
            g.SmoothingMode = SmoothingMode.AntiAlias;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;
            g.DrawImage(image,
                        new Rectangle(0, 0, _width, _height),
                        0, 0, image.Width, image.Height,
                        GraphicsUnit.Pixel);

            image = (Image)bmPhoto;
            return image;
        }
Exemplo n.º 4
0
        private void ResizeWithSystemDrawing(string filePath, string resizedFilePath, int size)
        {
            var image = DrawingImage.FromFile(filePath);

            var destRect  = new DrawingRectangle(0, 0, size, size);
            var destImage = new DrawingBitmap(size, size);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = DrawingGraphics.FromImage(destImage))
            {
                graphics.CompositingMode    = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode      = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            destImage.Save(resizedFilePath);
        }
Exemplo n.º 5
0
    protected void btnCrop_Click(object sender, EventArgs e)
    {
        using (Image img = Image.FromFile(Server.MapPath(Global.PROFILE_PICTURE + SessionClass.getUserId() + Global.PICTURE_EXTENSION_JPG)))
        {
            using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(Convert.ToInt32(Request.Form["w"]), Convert.ToInt32(Request.Form["h"])))
            {
                _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                using (Graphics _graphic = Graphics.FromImage(_bitmap))
                {
                    _graphic.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    _graphic.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    _graphic.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    _graphic.DrawImage(img, 0, 0, Convert.ToInt32(Request.Form["w"]), Convert.ToInt32(Request.Form["h"]));
                    _graphic.DrawImage(img, new Rectangle(0, 0, Convert.ToInt32(Request.Form["w"]), Convert.ToInt32(Request.Form["h"])), System.Math.Min(Convert.ToInt32(Request.Form["x1"]), Convert.ToInt32(Request.Form["x2"])), System.Math.Min(Convert.ToInt32(Request["y1"]), Convert.ToInt32(Request.Form["y2"])), Convert.ToInt32(Request.Form["w"]), Convert.ToInt32(Request.Form["h"]), GraphicsUnit.Pixel);

                    using (EncoderParameters encoderParameters = new EncoderParameters(1))
                    {
                        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                        _bitmap.Save(string.Concat(Server.MapPath("cropped/"), SessionClass.getUserId(), Global.PICTURE_EXTENSION_JPG), GetImageCodec(Global.PICTURE_EXTENSION_JPG), encoderParameters);
                    }
                }
            }
        }

        if (File.Exists(Server.MapPath(Global.PROFILE_PICTURE + SessionClass.getUserId() + Global.PICTURE_EXTENSION_JPG)))
        {
            File.Delete(Server.MapPath(Global.PROFILE_PICTURE + SessionClass.getUserId() + Global.PICTURE_EXTENSION_JPG));
        }
    }
Exemplo n.º 6
0
        /// <summary>
        /// Resizes and rotates an image, keeping the original aspect ratio. Does not dispose the original
        /// Image instance.
        /// </summary>
        /// <param name="image">Image instance</param>
        /// <param name="width">desired width</param>
        /// <param name="height">desired height</param>
        /// <param name="rotateFlipType">desired RotateFlipType</param>
        /// <returns>new resized/rotated Image instance</returns>
        public static System.Drawing.Image Resize(System.Drawing.Image image, int width, 
            int height, RotateFlipType rotateFlipType)
        {
            // clone the Image instance, since we don't want to resize the original Image instance
            var rotatedImage = image.Clone() as System.Drawing.Image;
            //rotatedImage.RotateFlip(rotateFlipType);
            var newSize = CalculateResizedDimensions(rotatedImage, width, height);

            var resizedImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format32bppArgb);
            resizedImage.SetResolution(72, 72);

            using (var graphics = Graphics.FromImage(resizedImage))
            {
                // set parameters to create a high-quality thumbnail
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.AntiAlias;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                // use an image attribute in order to remove the black/gray border around image after resize
                // (most obvious on white images), see this post for more information:
                // http://www.codeproject.com/KB/GDI-plus/imgresizoutperfgdiplus.aspx
                using (var attribute = new ImageAttributes())
                {
                    attribute.SetWrapMode(WrapMode.TileFlipXY);

                    // draws the resized image to the bitmap
                    graphics.DrawImage(rotatedImage, new Rectangle(new Point(0, 0), newSize), 0, 0, rotatedImage.Width, rotatedImage.Height, GraphicsUnit.Pixel, attribute);
                }
            }

            return resizedImage;
        }
Exemplo n.º 7
0
 private static byte[] Crop(string img, int width, int height, int X, int Y)
 {
     try
     {
         using (SD.Image originalImage = SD.Image.FromFile(img))
         {
             using (SD.Bitmap bmp = new SD.Bitmap(width, height))
             {
                 bmp.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
                 using (SD.Graphics graphic = SD.Graphics.FromImage(bmp))
                 {
                     graphic.SmoothingMode     = SmoothingMode.AntiAlias;
                     graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                     graphic.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                     graphic.DrawImage(originalImage, new SD.Rectangle(0, 0, width, height), X, Y, width, height, SD.GraphicsUnit.Pixel);
                     MemoryStream ms = new MemoryStream();
                     bmp.Save(ms, originalImage.RawFormat);
                     return(ms.GetBuffer());
                 }
             }
         }
     }
     catch (Exception Ex)
     {
         throw (Ex);
     }
 }
Exemplo n.º 8
0
 static byte[] CropImage(string sImagePath, int iWidth, int iHeight, int iX, int iY)
 {
     try
     {
         using (System.Drawing.Image oOriginalImage = System.Drawing.Image.FromFile(sImagePath))
         {
             using (System.Drawing.Bitmap oBitmap = new System.Drawing.Bitmap(iWidth, iHeight))
             {
                 oBitmap.SetResolution(oOriginalImage.HorizontalResolution, oOriginalImage.VerticalResolution);
                 using (System.Drawing.Graphics Graphic = System.Drawing.Graphics.FromImage(oBitmap))
                 {
                     Graphic.SmoothingMode     = SmoothingMode.AntiAlias;
                     Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                     Graphic.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                     Graphic.DrawImage(oOriginalImage, new System.Drawing.Rectangle(0, 0, iWidth, iHeight), iX, iY, iWidth, iHeight, System.Drawing.GraphicsUnit.Pixel);
                     MemoryStream oMemoryStream = new MemoryStream();
                     oBitmap.Save(oMemoryStream, oOriginalImage.RawFormat);
                     return(oMemoryStream.GetBuffer());
                 }
             }
         }
     }
     catch (Exception Ex)
     {
         throw (Ex);
     }
 }
Exemplo n.º 9
0
        /// <summary>
        /// Saves the graph as an bitmap file and returns the bitmap.
        /// </summary>
        /// <param name="doc">The graph document to export.</param>
        /// <param name="dpiResolution">Resolution of the bitmap in dpi. Determines the pixel size of the bitmap.</param>
        /// <param name="backbrush">Brush used to fill the background of the image. Can be <c>null</c>.</param>
        /// <param name="pixelformat">Specify the pixelformat here.</param>
        /// <returns>The saved bitmap. You should call Dispose when you no longer need the bitmap.</returns>
        public static System.Drawing.Bitmap SaveAsBitmap(GraphDocument doc, int dpiResolution, Brush backbrush, PixelFormat pixelformat)
        {
            double scale = dpiResolution / 72.0;
            // Code to write the stream goes here.

            // round the pixels to multiples of 4, many programs rely on this
            int width  = (int)(4 * Math.Ceiling(0.25 * doc.PageBounds.Width * scale));
            int height = (int)(4 * Math.Ceiling(0.25 * doc.PageBounds.Height * scale));

            System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, pixelformat);
            bitmap.SetResolution(dpiResolution, dpiResolution);

            Graphics grfx = Graphics.FromImage(bitmap);

            if (null != backbrush)
            {
                grfx.FillRectangle(backbrush, new Rectangle(0, 0, width, height));
            }

            grfx.PageUnit = GraphicsUnit.Point;
            grfx.TranslateTransform(doc.PrintableBounds.X, doc.PrintableBounds.Y);
            grfx.PageScale = 1; // (float)scale;


            doc.DoPaint(grfx, true);

            grfx.Dispose();

            return(bitmap);
        }
Exemplo n.º 10
0
        public static Image ResizeImage(Image img, int width, int height)
        {
            if (width < 1 || height < 1 || (img.Width == width && img.Height == height))
            {
                return img;
            }

            Bitmap bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);

            using (img)
            using (Graphics g = Graphics.FromImage(bmp))
            {
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.SmoothingMode = SmoothingMode.HighQuality;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.CompositingMode = CompositingMode.SourceOver;

                using (ImageAttributes ia = new ImageAttributes())
                {
                    ia.SetWrapMode(WrapMode.TileFlipXY);
                    g.DrawImage(img, new Rectangle(0, 0, width, height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia);
                }
            }

            return bmp;
        }
Exemplo n.º 11
0
        public static Image ScaleByPercent(Image imgPhoto, int Percent, InterpolationMode interpolationMode)
        {
            float nPercent = ((float)Percent / 100);

            int sourceWidth = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX = 0;
            int sourceY = 0;

            int destX = 0;
            int destY = 0;
            int destWidth = (int)(sourceWidth * nPercent);
            int destHeight = (int)(sourceHeight * nPercent);

            Bitmap bmPhoto = new Bitmap(destWidth, destHeight,
                                     System.Drawing.Imaging.PixelFormat.Format24bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                                    imgPhoto.VerticalResolution);

            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.InterpolationMode = interpolationMode;

            //int memoryMB = (int)(Process.GetCurrentProcess().PagedMemorySize64 / (1024 * 1024));

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
Exemplo n.º 12
0
        /// <summary>
        /// Draw Reflection
        /// </summary>
        /// <param name="img">Set Image</param>
        /// <param name="toBG">Set Color of Background</param>
        /// <param name="RotateFlipType">Rotation Type. Default value is Rotate180FlipX</param>
        /// <param name="LinearGradientMode">Gradient Mode. Default value is Vertical</param>
        /// <param name="Length">Length of the Mirror. Default value is 100</param>
        /// <returns></returns>
        public static Image DrawReflection(Image img, Color toBG,
                                           RotateFlipType RotateFlipType         = RotateFlipType.Rotate180FlipX,
                                           LinearGradientMode LinearGradientMode = LinearGradientMode.Vertical,
                                           int Length = 100) // img is the original image.
        {
            //This is the static function that generates the reflection...
            int height = img.Height + Length;                                                                                               //Added height from the original height of the image.

            System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(img.Width, height, PixelFormat.Format64bppPArgb);                         //A new bitmap.
            Brush brsh = new LinearGradientBrush(new Rectangle(0, 0, img.Width + 10, height), Color.Transparent, toBG, LinearGradientMode); //The Brush that generates the fading effect to a specific color of your background.

            bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);                                                            //Sets the new bitmap's resolution.
            using (System.Drawing.Graphics grfx = System.Drawing.Graphics.FromImage(bmp))                                                   //A graphics to be generated from an image (here, the new Bitmap we've created (bmp)).
            {
                System.Drawing.Bitmap bm = (System.Drawing.Bitmap)img;                                                                      //Generates a bitmap from the original image (img).
                grfx.DrawImage(bm, 0, 0, img.Width, img.Height);                                                                            //Draws the generated bitmap (bm) to the new bitmap (bmp).
                System.Drawing.Bitmap bm1 = (System.Drawing.Bitmap)img;                                                                     //Generates a bitmap again from the original image (img).
                bm1.RotateFlip(RotateFlipType);                                                                                             //Flips and rotates the image (bm1).
                grfx.DrawImage(bm1, 0, img.Height);                                                                                         //Draws (bm1) below (bm) so it serves as the reflection image.
                Rectangle rt = new Rectangle(0, img.Height, img.Width, Length);                                                             //A new rectangle to paint our gradient effect.
                grfx.FillRectangle(brsh, rt);                                                                                               //Brushes the gradient on (rt).
            }

            return(bmp); //Returns the (bmp) with the generated image.
        }
Exemplo n.º 13
0
        public static Bitmap RotateImage(Image image, float rotateAtX, float rotateAtY, float angle, bool bNoClip)
        {
            int W, H, X, Y;
            if (bNoClip)
            {
                double dW = (double)image.Width;
                double dH = (double)image.Height;

                double degrees = Math.Abs(angle);
                if (degrees <= 90)
                {
                    double radians = 0.0174532925 * degrees;
                    double dSin = Math.Sin(radians);
                    double dCos = Math.Cos(radians);
                    W = (int)(dH * dSin + dW * dCos);
                    H = (int)(dW * dSin + dH * dCos);
                    X = (W - image.Width) / 2;
                    Y = (H - image.Height) / 2;
                }
                else
                {
                    degrees -= 90;
                    double radians = 0.0174532925 * degrees;
                    double dSin = Math.Sin(radians);
                    double dCos = Math.Cos(radians);
                    W = (int)(dW * dSin + dH * dCos);
                    H = (int)(dH * dSin + dW * dCos);
                    X = (W - image.Width) / 2;
                    Y = (H - image.Height) / 2;
                }
            }
            else
            {
                W = image.Width;
                H = image.Height;
                X = 0;
                Y = 0;
            }

            //create a new empty bitmap to hold rotated image
            Bitmap bmpRet = new Bitmap(W, H);
            bmpRet.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            //make a graphics object from the empty bitmap
            Graphics g = Graphics.FromImage(bmpRet);

            //Put the rotation point in the "center" of the image
            g.TranslateTransform(rotateAtX + X, rotateAtY + Y);

            //rotate the image
            g.RotateTransform(angle);

            //move the image back
            g.TranslateTransform(-rotateAtX - X, -rotateAtY - Y);

            //draw passed in image onto graphics object
            g.DrawImage(image, new PointF(0 + X, 0 + Y));

            return bmpRet;
        }
Exemplo n.º 14
0
    static byte[] Crop(string Img, int Width, int Height, int X, int Y)
    {
        using (SD.Image OriginalImage = SD.Image.FromFile(Img))
        {
            using (SD.Bitmap bmp = new SD.Bitmap(Width, Height))
            {
                bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);

                using (SD.Graphics Graphic = SD.Graphics.FromImage(bmp))
                {
                    Graphic.SmoothingMode = SmoothingMode.AntiAlias;

                    Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;

                    Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;

                    Graphic.DrawImage(OriginalImage, new SD.Rectangle(0, 0, Width, Height), X, Y, Width, Height, SD.GraphicsUnit.Pixel);

                    MemoryStream ms = new MemoryStream();

                    bmp.Save(ms, OriginalImage.RawFormat);

                    return(ms.GetBuffer());
                }
            }
        }
    }
Exemplo n.º 15
0
        ///<summary></summary>
        public static void DrawBitmap(TextFrame frameContainer, System.Drawing.Bitmap bitmap, float xPos, float yPos)
        {
            string imageFileName = PrefC.GetRandomTempFile(".tmp");

            bitmap.SetResolution(100, 100);           //prevents framework from scaling it.
            bitmap.Save(imageFileName);
            TextFrame frame = new TextFrame();

            frame.AddImage(imageFileName);
            frame.RelativeVertical   = RelativeVertical.Page;
            frame.RelativeHorizontal = RelativeHorizontal.Page;
            frame.MarginLeft         = Unit.FromInch(xPos / 100);
            frame.MarginTop          = Unit.FromInch(yPos / 100);
            frame.Top   = TopPosition.Parse("0 in");
            frame.Left  = LeftPosition.Parse("0 in");
            frame.Width = frameContainer.Width;
            Unit bottom = Unit.FromInch((yPos + (double)bitmap.Height) / 100);

            if (frameContainer.Height < bottom)
            {
                frameContainer.Height = bottom;
            }
            frame.Height = frameContainer.Height;
            //LineFormat lineformat=new LineFormat();
            //lineformat.Width=1;
            //frame.LineFormat=lineformat;
            frameContainer.Elements.Add(frame);
        }
 public static Bitmap Resample(Bitmap source, int dpiX, int dpiY)
 {
     ImageUtil.log.Info(string.Concat(new object[4]
       {
     (object) "Old Width: ",
     (object) source.Width,
     (object) " Old Height: ",
     (object) source.Height
       }));
       int width1 = source.Width;
       int height1 = source.Height;
       double num = 1.0;
       if (source.Width > 800)
     num = 800.0 / (double) source.Width;
       else if (source.Height > 800)
     num = 800.0 / (double) source.Height;
       int width2 = (int) Math.Round((double) source.Width * num);
       int height2 = (int) Math.Round((double) source.Height * num);
       ImageUtil.log.Info(string.Concat(new object[4]
       {
     (object) "New Width: ",
     (object) width2,
     (object) " New Height: ",
     (object) height2
       }));
       Bitmap bitmap = new Bitmap(width2, height2);
       bitmap.SetResolution((float) dpiX, (float) dpiY);
       Graphics graphics = Graphics.FromImage((Image) bitmap);
       graphics.Clear(Color.White);
       graphics.DrawImage((Image) source, new Rectangle(0, 0, width2, height2), new Rectangle(0, 0, source.Width, source.Height), GraphicsUnit.Pixel);
       return bitmap;
 }
Exemplo n.º 17
0
        byte[] GetResizedImage(Stream originalStream, ImageFormat imageFormat, int width, int height)
        {
            Bitmap imgIn = new Bitmap(originalStream);
            double y = imgIn.Height;
            double x = imgIn.Width;

            double factor = 1;
            if (width > 0)
            {
                factor = width / x;
            }
            else if (height > 0)
            {
                factor = height / y;
            }
            System.IO.MemoryStream outStream = new System.IO.MemoryStream();
            Bitmap imgOut = new Bitmap((int)(x * factor), (int)(y * factor));

            // Set DPI of image (xDpi, yDpi)
            imgOut.SetResolution(72, 72);

            Graphics g = Graphics.FromImage(imgOut);
            g.Clear(Color.White);
            g.DrawImage(imgIn, new Rectangle(0, 0, (int)(factor * x), (int)(factor * y)),
              new Rectangle(0, 0, (int)x, (int)y), GraphicsUnit.Pixel);

            imgOut.Save(outStream, imageFormat);
            return outStream.ToArray();
        }
Exemplo n.º 18
0
		/// <summary>
		/// 等比率縮小放大
		/// </summary>
		/// <param name="imgPhoto">原圖</param>
		/// <param name="Percent">比率</param>
		/// <returns>放大縮小的結果</returns>
		public Image ScaleByPercent(Image imgPhoto, int Percent)
		{
			float nPercent = ((float)Percent/100);

			int sourceWidth = imgPhoto.Width;
			int sourceHeight = imgPhoto.Height;
			int sourceX = 0;
			int sourceY = 0;

			int destX = 0;
			int destY = 0; 
			int destWidth  = (int)(sourceWidth * nPercent);
			int destHeight = (int)(sourceHeight * nPercent);

			Bitmap bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format24bppRgb);
			bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

			Graphics grPhoto = Graphics.FromImage(bmPhoto);
			grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

			grPhoto.DrawImage(imgPhoto, 
				new Rectangle(destX,destY,destWidth,destHeight),
				new Rectangle(sourceX,sourceY,sourceWidth,sourceHeight),
				GraphicsUnit.Pixel);

			grPhoto.Dispose();
			return bmPhoto;
		}
        public static Bitmap RotateImage(Image image, PointF offset, float angle)
        {
            if (image == null)
                throw new ArgumentNullException("image");

            //create a new empty bitmap to hold rotated image
            Bitmap rotatedBmp = new Bitmap(image.Width, image.Height);
            rotatedBmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            //make a graphics object from the empty bitmap
            Graphics g = Graphics.FromImage(rotatedBmp);

            //Put the rotation point in the center of the image
            g.TranslateTransform(offset.X, offset.Y);

            //rotate the image
            g.RotateTransform(angle);

            //move the image back
            g.TranslateTransform(-offset.X, -offset.Y);

            //draw passed in image onto graphics object
            g.DrawImage(image, new PointF(0, 0));

            return rotatedBmp;
        }
Exemplo n.º 20
0
 public static bool Crop(string _img, string img, int width, int height, int x, int y)
 {
     try
     {
         using (Image OriginalImage = Image.FromFile(_img))
         {
             using (Bitmap bmp = new Bitmap(width, height))
             {
                 bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
                 using (Graphics Graphic = Graphics.FromImage(bmp))
                 {
                     Graphic.SmoothingMode = SmoothingMode.AntiAlias;
                     Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                     Graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
                     Graphic.DrawImage(OriginalImage, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
                     MemoryStream ms = new MemoryStream();
                     bmp.Save(ms, OriginalImage.RawFormat);
                     if (File.Exists(img))
                         File.Delete(img);
                     File.WriteAllBytes(img, ms.GetBuffer());
                     return true;
                 }
             }
         }
     }
     catch (Exception Ex)
     {
         return false;
     }
 }
Exemplo n.º 21
0
        /// <summary>
        /// Resize the image to the specified width and height.
        /// </summary>
        /// <param name="image">The image to resize.</param>
        /// <param name="width">The width to resize to.</param>
        /// <param name="height">The height to resize to.</param>
        /// <returns>The resized image.</returns>
        public static System.Drawing.Image ResizeImage(this System.Drawing.Image image, int width, int height)
        {
            if ((image.Height < height) && (image.Width < width))
                return image;
            var destRect = new Rectangle(0, 0, width, height);
            var destImage = new Bitmap(width, height);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }
            return destImage;
        }
Exemplo n.º 22
0
        /// <summary>
        ///     The G910 also updates the G-logo, G-badge and G-keys
        /// </summary>
        /// <param name="bitmap"></param>
        public override void DrawBitmap(Bitmap bitmap)
        {
            using (var croppedBitmap = new Bitmap(21*4, 6*4))
            {
                // Deal with non-standard DPI
                croppedBitmap.SetResolution(96, 96);
                // Don't forget that the image is upscaled 4 times
                using (var g = Graphics.FromImage(croppedBitmap))
                {
                    g.DrawImage(bitmap, new Rectangle(0, 0, 84, 24), new Rectangle(4, 4, 84, 24), GraphicsUnit.Pixel);
                }

                base.DrawBitmap(croppedBitmap);
            }

            using (var resized = OrionUtilities.ResizeImage(bitmap, 22, 7))
            {
                // Color the extra keys on the left side of the keyboard
                SetLogitechColorFromCoordinates(resized, KeyboardNames.G_LOGO, 0, 1);
                SetLogitechColorFromCoordinates(resized, KeyboardNames.G_1, 0, 2);
                SetLogitechColorFromCoordinates(resized, KeyboardNames.G_2, 0, 3);
                SetLogitechColorFromCoordinates(resized, KeyboardNames.G_3, 0, 4);
                SetLogitechColorFromCoordinates(resized, KeyboardNames.G_4, 0, 5);
                SetLogitechColorFromCoordinates(resized, KeyboardNames.G_5, 0, 6);

                // Color the extra keys on the top of the keyboard
                SetLogitechColorFromCoordinates(resized, KeyboardNames.G_6, 3, 0);
                SetLogitechColorFromCoordinates(resized, KeyboardNames.G_7, 4, 0);
                SetLogitechColorFromCoordinates(resized, KeyboardNames.G_8, 5, 0);
                SetLogitechColorFromCoordinates(resized, KeyboardNames.G_9, 6, 0);

                // Color the G-badge
                SetLogitechColorFromCoordinates(resized, KeyboardNames.G_BADGE, 5, 6);
            }
        }
        // POST api/imagerecognition
        public double[] Post([FromBody]object text)
        {
            var txt = System.Web.HttpContext.Current.Request.Form["text"];
            txt = txt.Substring("data:image/png;base64,".Count());
            var imgData = Convert.FromBase64String(txt);
            var path = System.Web.Hosting.HostingEnvironment.MapPath("~/") + "\\tempimg.png";
            var path1 = System.Web.Hosting.HostingEnvironment.MapPath("~/") + "\\tempimg.bmp";

            using (var img = System.IO.File.OpenWrite(path))
            {
                img.Write(imgData, 0, imgData.Count());
                img.Close();
                img.Dispose();
            }

            Image img1 = Image.FromFile(path);
            using (Bitmap b = new Bitmap(img1.Width, img1.Height))
            {
                b.SetResolution(img1.HorizontalResolution, img1.VerticalResolution);

                using (Graphics g = Graphics.FromImage(b))
                {
                    g.Clear(Color.White);
                    g.DrawImageUnscaled(img1, 0, 0);
                }

                b.Save(path1,System.Drawing.Imaging.ImageFormat.Bmp);
                // Now save b as a JPEG like you normally would
            }
            img1.Dispose();

            return ImageRecognitionContext.OCR.RecognizeImage(Image.FromFile(path1));
        }
Exemplo n.º 24
0
        public static System.Drawing.Image ProcessCrop(System.Drawing.Image imgPhoto, int Width, int Height, int X, int Y)
        {
            int sourceWidth  = imgPhoto.Width;
            int sourceHeight = imgPhoto.Height;
            int sourceX      = 0;
            int sourceY      = 0;
            int destX        = X;
            int destY        = Y;

            System.Drawing.Bitmap bmPhoto = new System.Drawing.Bitmap(
                Width, Height, PixelFormat.Format32bppRgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            System.Drawing.Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.Clear(System.Drawing.Color.White);
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
            //InterpolationMode.HighQualityBicubic;
            // grPhoto.CompositingQuality =CompositingQuality.HighQuality ;
            //grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
            grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
            grPhoto.CompositingMode = CompositingMode.SourceOver;
            //grPhoto.DrawImage(imgPhoto,
            //    new System.Drawing.Rectangle(destX, destY, Width, Height),
            //    new System.Drawing.Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
            //    System.Drawing.GraphicsUnit.Pixel);
            grPhoto.DrawImage(imgPhoto,
                              new System.Drawing.Rectangle(sourceX, sourceY, Width, Height),
                              new System.Drawing.Rectangle(destX, destY, Width, Height),
                              System.Drawing.GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return(bmPhoto);
        }
Exemplo n.º 25
0
        private static Image ToFixedSize(this Image imgPhoto, int width, int height)
        {
            var dimensions = ResizeKeepAspect(imgPhoto.Size, width, height);

            var bmPhoto = new Bitmap(width, height,
                PixelFormat.Format24bppRgb);

            bmPhoto.SetResolution(imgPhoto.HorizontalResolution,
                imgPhoto.VerticalResolution);

            using (var grPhoto = Graphics.FromImage(bmPhoto))
            {
                grPhoto.Clear(Color.White);
                grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

                grPhoto.DrawImage(imgPhoto,
                    new RectangleF(dimensions.X, dimensions.Y, dimensions.Width, dimensions.Height),
                    new RectangleF(0, 0, imgPhoto.Width, imgPhoto.Height),
                    GraphicsUnit.Pixel);
            }

            imgPhoto.Dispose();

            return bmPhoto;
        }
        protected void CropCommandClick(object sender, EventArgs e)
        {
            var x = int.Parse(_xField.Value);
            var y = int.Parse(_yField.Value);
            var width = int.Parse(_widthField.Value);
            var height = int.Parse(_heightField.Value);

            using (var photo = Image.FromFile(Server.MapPath("~/Images/akropolis-doggie.jpg")))
            using (var result = new Bitmap(width, height, photo.PixelFormat))
            {
                result.SetResolution(
                        photo.HorizontalResolution,
                        photo.VerticalResolution);

                using (var g = Graphics.FromImage(result))
                {
                    g.InterpolationMode =
                         InterpolationMode.HighQualityBicubic;
                    g.DrawImage(photo,
                         new Rectangle(0, 0, width, height),
                         new Rectangle(x, y, width, height),
                         GraphicsUnit.Pixel);
                    photo.Dispose();

                    result.Save(Server.MapPath("~/Images/cropped_doggie.jpg"));
                }
            }
        }
Exemplo n.º 27
0
        //Метод для высококачественного изменения размера изображения
        public static Image ResizeImage(Image image, int width, int height)
        {
            //Если изменять нечего, возвращаем исходное изображение без изменений
            if ((image.Width == width && image.Height == height) || (width == 0 && height == 0))
                return new Bitmap(image);

            var destRect = new Rectangle(0, 0, width, height);
            var destImage = new Bitmap(width, height);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            return destImage;
        }
Exemplo n.º 28
0
        //    1) Prevent anti-aliasing.
        //...
        //g.InterpolationMode = InterpolationMode.HighQualityBicubic;
        //// add below line
        //g.CompositingMode = CompositingMode.SourceCopy;
        //...
        //http://stackoverflow.com/questions/4772273/interpolationmode-highqualitybicubic-introducing-artefacts-on-edge-of-resized-im


        ////resize the image to the specified height and width
        //using (var resized = ImageUtilities.ResizeImage(image, 50, 100))
        //{
        //    //save the resized image as a jpeg with a quality of 90
        //    ImageUtilities.SaveJpeg(@"C:\myimage.jpeg", resized, 90);
        //}

        // Sourced from:
        // http://stackoverflow.com/questions/249587/high-quality-image-scaling-c-sharp

        /// <summary>
        /// Resize the image to the specified width and height.
        /// </summary>
        /// <param name="image">The image to resize.</param>
        /// <param name="size">The width and height to resize to.</param>
        /// <returns>The resized image.</returns>
        public static Bitmap ResizeImage(Image image, Size size)
        {
            if (size.Width < 1 || size.Height < 1)
            {
                return null;
            }

            // a holder for the result
            var result = new Bitmap(size.Width, size.Height);
            //set the resolutions the same to avoid cropping due to resolution differences
            result.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            //use a graphics object to draw the resized image into the bitmap
            using (Graphics graphics = Graphics.FromImage(result))
            {
                //set the resize quality modes to high quality
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //draw the image into the target bitmap
                graphics.DrawImage(image, 0, 0, result.Width, result.Height);
            }

            //return the resulting bitmap
            return result;
        }
Exemplo n.º 29
0
        public void AddBackGroundToPic(int width, int height, string picType, int destLength, string backPicURl)
        {
            bmpTemp = new Bitmap(destLength, destLength, PixelFormat.Format32bppArgb);

            bmpTemp.SetResolution(imgSource.HorizontalResolution, imgSource.VerticalResolution);
            bmpTemp.MakeTransparent(Color.White);

            // 建立Graphics对象,并设置主要属性
            Graphics g = Graphics.FromImage(bmpTemp);
            try
            {
                g.Clear(Color.White);
                g.InterpolationMode = InterpolationMode.HighQualityBicubic;
                g.CompositingQuality = CompositingQuality.GammaCorrected;
                g.PixelOffsetMode = PixelOffsetMode.HighQuality;
                g.SmoothingMode = SmoothingMode.HighQuality;

                // 在画布上画图
                //设置背景图片
                g.DrawImage(Image.FromFile(backPicURl + picType + ".png"), 0, 0);
                g.DrawImage(imgSource, (destLength - Convert.ToSingle(width)) / 2, (destLength - Convert.ToSingle(height)) / 2, Convert.ToSingle(width), Convert.ToSingle(height));
                imgSource.Dispose();
                imgSource = (Image)bmpTemp.Clone();
            }
            catch (Exception exp)
            {
                throw exp;
            }
            finally
            {
                g.Dispose();
                bmpTemp.Dispose();
            }
        }
        // convert byte array to 8 bit grayscale bitmap
        protected Bitmap fCreateBitmap(byte[] bArray, int[] iSize, float[] fRes)
        {
            int iWidth  = iSize[0];
            int iHeight = iSize[1];

            // create new bitmap
            System.Drawing.Bitmap bmBitmap = new System.Drawing.Bitmap(iWidth, iHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);
            bmBitmap.SetResolution(fRes[0], fRes[1]);

            // create new bitmap data
            BitmapData bmData = bmBitmap.LockBits(new System.Drawing.Rectangle(0, 0, iWidth, iHeight), ImageLockMode.ReadWrite, System.Drawing.Imaging.PixelFormat.Format8bppIndexed);

            // copy data
            Marshal.Copy(bArray, 0, bmData.Scan0, (int)(iWidth * iHeight));
            bmBitmap.UnlockBits(bmData);

            // create grayscale color palette
            ColorPalette _palette = bmBitmap.Palette;

            System.Drawing.Color[] _entries = _palette.Entries;
            for (int i = 0; i < 256; i++)
            {
                System.Drawing.Color b = new System.Drawing.Color();
                b           = System.Drawing.Color.FromArgb((byte)i, (byte)i, (byte)i);
                _entries[i] = b;
            }
            bmBitmap.Palette = _palette;

            // return bitmap
            return(bmBitmap);
        }
Exemplo n.º 31
0
 public static byte[] ResizeImageFile(byte[] imageFile, int targetSize)
 {
     Image original = Image.FromStream(new MemoryStream(imageFile));
     int targetH, targetW;
     if (original.Height > original.Width)
     {
         targetH = targetSize;
         targetW = (int)(original.Width * ((float)targetSize / (float)original.Height));
     }
     else
     {
         targetW = targetSize;
         targetH = (int)(original.Height * ((float)targetSize / (float)original.Width));
     }
     Image imgPhoto = Image.FromStream(new MemoryStream(imageFile));
     // Create a new blank canvas.  The resized image will be drawn on this canvas.
     Bitmap bmPhoto = new Bitmap(targetW, targetH, PixelFormat.Format24bppRgb);
     bmPhoto.SetResolution(72, 72);
     Graphics grPhoto = Graphics.FromImage(bmPhoto);
     grPhoto.SmoothingMode = SmoothingMode.AntiAlias;
     grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
     grPhoto.PixelOffsetMode = PixelOffsetMode.HighQuality;
     grPhoto.DrawImage(imgPhoto, new Rectangle(0, 0, targetW, targetH), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel);
     // Save out to memory and then to a file.  We dispose of all objects to make sure the files don't stay locked.
     MemoryStream mm = new MemoryStream();
     bmPhoto.Save(mm, System.Drawing.Imaging.ImageFormat.Jpeg);
     original.Dispose();
     imgPhoto.Dispose();
     bmPhoto.Dispose();
     grPhoto.Dispose();
     return mm.GetBuffer();
 }
Exemplo n.º 32
0
        public static Image ScaleByPercent(Image imgPhoto, int Percent)
        {
            var nPercent = ((float)Percent / 100);

            var sourceWidth = imgPhoto.Width;
            var sourceHeight = imgPhoto.Height;
            var sourceX = 0;
            var sourceY = 0;

            var destX = 0;
            var destY = 0;
            var destWidth = (int)(sourceWidth * nPercent + 0.5);
            var destHeight = (int)(sourceHeight * nPercent + 0.5);

            var bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format32bppArgb);
            bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
            bmPhoto.MakeTransparent();
            Graphics grPhoto = Graphics.FromImage(bmPhoto);
            grPhoto.Clear(Color.Transparent);
            grPhoto.SmoothingMode = SmoothingMode.HighQuality;
            grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;

            grPhoto.DrawImage(imgPhoto,
                new Rectangle(destX, destY, destWidth, destHeight),
                new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
                GraphicsUnit.Pixel);

            grPhoto.Dispose();
            return bmPhoto;
        }
Exemplo n.º 33
0
        /// <summary>
        /// Processes the image.
        /// </summary>
        /// <param name="factory">
        /// The current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class containing
        /// the image to process.
        /// </param>
        /// <returns>
        /// The processed image from the current instance of the <see cref="T:ImageProcessor.ImageFactory"/> class.
        /// </returns>
        public Image ProcessImage(ImageFactory factory)
        {
            Bitmap newImage = null;
            Image image = factory.Image;

            try
            {
                // TODO: Optimize this one day when I can break the API.
                newImage = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppPArgb);
                newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
                IMatrixFilter matrix = this.DynamicParameter;
                newImage = matrix.TransformImage(image, newImage);
                
                image.Dispose();
                image = newImage;
            }
            catch (Exception ex)
            {
                if (newImage != null)
                {
                    newImage.Dispose();
                }

                throw new ImageProcessingException("Error processing image with " + this.GetType().Name, ex);
            }

            return image;
        }
Exemplo n.º 34
0
        private static Bitmap ResizeImage(Image image, int width, int height)
        {
            // Borrowed from http://stackoverflow.com/questions/1922040/resize-an-image-c-sharp
            // Ensures a high quality resizing.
            var destRect = new Rectangle(0, 0, width, height);
            var destImage = new Bitmap(width, height);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }
            return destImage;
        }
Exemplo n.º 35
0
        /// <summary>
        /// Resizes the image using a high quality.  
        /// From http://stackoverflow.com/questions/1922040/resize-an-image-c-sharp
        /// </summary>
        /// <param name="imageStream"></param>
        /// <returns></returns>
        internal static MemoryStream ProcessImage(MemoryStream imageStream)
        {
            var height = 100;
            var width = 100;

            Image original = Image.FromStream(imageStream);

            var destRect = new Rectangle(0, 0, width, height);
            var destImage = new Bitmap(width, height);

            destImage.SetResolution(original.HorizontalResolution, original.VerticalResolution);

            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(original, destRect, 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            MemoryStream ret = new MemoryStream();
            destImage.Save(ret, original.RawFormat);
            ret.FlushAsync().Wait();
            ret.Position = 0;
            return ret;
        }
Exemplo n.º 36
0
        /// <summary>
        /// Crops a provided image to the provided dimensions, starting at the provided X and Y position.
        /// </summary>
        /// <param name="imageBytes">The image to be cropped</param>
        /// <param name="width">The desired width of the cropped image</param>
        /// <param name="height">The desired height of the cropped image</param>
        /// <param name="X">The X position where the cropping will begin</param>
        /// <param name="Y">The Y position where the cropping will begin</param>
        /// <returns></returns>
        public static byte[] Crop(byte[] imageBytes, int width, int height, int X, int Y)
        {
            // Convert the bytes into an Image
            MemoryStream ms = new MemoryStream(imageBytes);

            System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);

            using (System.Drawing.Image OriginalImage = returnImage)
            {
                using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(width, height))
                {
                    bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
                    using (System.Drawing.Graphics Graphic = System.Drawing.Graphics.FromImage(bmp))
                    {
                        Graphic.SmoothingMode     = SmoothingMode.HighQuality;
                        Graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                        Graphic.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                        Graphic.DrawImage(OriginalImage, new System.Drawing.Rectangle(0, 0, width, height), X, Y, width, height, System.Drawing.GraphicsUnit.Pixel);
                        MemoryStream nms = new MemoryStream();
                        bmp.Save(nms, OriginalImage.RawFormat);
                        return(nms.GetBuffer());
                    }
                }
            }
        }
Exemplo n.º 37
0
		public Bitmap GetBitmap(Size size, int dpi)
		{
			Contract.Ensures(Contract.Result<Bitmap>() != null);
			Contract.Ensures((Contract.Result<Bitmap>().PixelFormat & PixelFormat.Indexed) == 0);

			Bitmap bitmap = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppRgb);
			bitmap.SetResolution(dpi, dpi);
			Contract.Assume((bitmap.PixelFormat & PixelFormat.Indexed) == 0);
			using (Graphics graphics = Graphics.FromImage(bitmap))
			{
				using (Pen pen = new Pen(Brushes.Black, (float)Math.Ceiling(dpi / 150d)))
				{
					foreach (Triangle triangle in this.Triangles)
					{
						triangle.DrawTriangle(graphics, size, 10000f * (float)Math.Ceiling(dpi / 300d), pen);
					}
				}

				Rectangle rect = new Rectangle(0, 0, size.Width, size.Height);
				LinearGradientBrush linearGradientBrush = new LinearGradientBrush(
					rect,
					Color.FromArgb(64, Color.Black),
					Color.FromArgb(0, Color.Black),
					LinearGradientMode.Vertical);

				graphics.FillRectangle(linearGradientBrush, rect);
			}

			Contract.Assume((bitmap.PixelFormat & PixelFormat.Indexed) == 0);
			return bitmap;
		}
Exemplo n.º 38
0
 ResizeImageWidthHeight(string imgPath, int resizeWidth,
                        int resizeHeight) //, int Width, int Height, int X, int Y)
 {
     try
     {
         using (var originalImage = sd.Image.FromFile(imgPath))
         {
             //int h = int.Parse(originalImage.Height.ToString()) / resize;
             //int w = int.Parse(originalImage.Width.ToString()) / resize;
             using (var bmp = new sd.Bitmap(resizeWidth, resizeHeight)) //(Width, Height))
             {
                 bmp.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
                 using (var graphic = sd.Graphics.FromImage(bmp))
                 {
                     graphic.SmoothingMode     = SmoothingMode.AntiAlias;
                     graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
                     graphic.PixelOffsetMode   = PixelOffsetMode.HighQuality;
                     graphic.DrawImage(originalImage,
                                       new sd.Rectangle(0, 0, resizeWidth,
                                                        resizeHeight)); //, X, Y, Width, Height, sd.GraphicsUnit.Pixel);
                     var ms = new MemoryStream();
                     bmp.Save(ms, originalImage.RawFormat);
                     return(ms.GetBuffer());
                 }
             }
         }
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
Exemplo n.º 39
0
        private static Size GetTexSize(IEnumerable <int> codePointList, int resolution, System.Drawing.Font font, SD.StringFormat sf, int leading)
        {
            int   texWidth, texHeight;
            float totalWidth = 0;

            using (var fontBitmap = new SD.Bitmap(1, 1))
            {
                fontBitmap.SetResolution(resolution, resolution);
                using (var g = SD.Graphics.FromImage(fontBitmap))
                {
                    g.InterpolationMode  = InterpolationMode.Low;
                    g.CompositingQuality = CompositingQuality.HighSpeed;
                    g.SmoothingMode      = SmoothingMode.HighSpeed;
                    g.PixelOffsetMode    = PixelOffsetMode.None;
                    g.TextRenderingHint  = TextRenderingHint.AntiAlias;
                    g.PageUnit           = SD.GraphicsUnit.Pixel;

                    foreach (int i in codePointList)
                    {
                        string c    = char.ConvertFromUtf32(i);
                        var    size = g.MeasureString(c, font, 4096, sf);
                        totalWidth += size.Width + 2;
                    }

                    double s = totalWidth * ((leading * 1.5) + 2);
                    texWidth  = Math.Sqrt(s).NextPowerOfTwo();
                    texHeight = (s / texWidth).NextPowerOfTwo();
                }
            }

            return(new Size(texWidth, texHeight));
        }
Exemplo n.º 40
0
        private static Bitmap ResizeImage(Image image, Rectangle rect)
        {
            var destImage = new Bitmap(rect.Width, rect.Height);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);

                    var destRectangle = new Rectangle(0, 0, rect.Width, rect.Height);
                    graphics.DrawImage(image, destRectangle, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            return destImage;
        }
Exemplo n.º 41
0
        /// <summary>
        /// Resizes an image
        /// </summary>
        /// <param name="image">The image to resize</param>
        /// <param name="width">New width in pixels</param>
        /// <param name="height">New height in pixesl</param>
        /// <param name="useHighQuality">Resize quality</param>
        /// <returns>The resized image</returns>
        public static Bitmap Resize(this Bitmap image, int width, int height, bool useHighQuality)
        {
            var newImg = new Bitmap(width, height);

            newImg.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var g = Graphics.FromImage(newImg))
            {
                g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
                if (useHighQuality)
                {
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                }
                else
                {
                    g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default;
                    g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.Default;
                    g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default;
                    g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Default;
                }

                var attributes = new ImageAttributes();
                attributes.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
                g.DrawImage(image, new System.Drawing.Rectangle(0, 0, width, height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
            }

            return newImg;
        }
Exemplo n.º 42
0
        private static Image LoadImagePriv(Stream s)
        {
            // Image.FromStream wants the stream to be open during
            // the whole lifetime of the image; as we can't guarantee
            // this, we make a copy of the image
            Image imgSrc = null;
            try
            {
            #if !KeePassLibSD
                imgSrc = Image.FromStream(s);
                Bitmap bmp = new Bitmap(imgSrc.Width, imgSrc.Height,
                    PixelFormat.Format32bppArgb);

                try
                {
                    bmp.SetResolution(imgSrc.HorizontalResolution,
                        imgSrc.VerticalResolution);
                    Debug.Assert(bmp.Size == imgSrc.Size);
                }
                catch(Exception) { Debug.Assert(false); }
            #else
                imgSrc = new Bitmap(s);
                Bitmap bmp = new Bitmap(imgSrc.Width, imgSrc.Height);
            #endif

                using(Graphics g = Graphics.FromImage(bmp))
                {
                    g.Clear(Color.Transparent);
                    g.DrawImage(imgSrc, 0, 0);
                }

                return bmp;
            }
            finally { if(imgSrc != null) imgSrc.Dispose(); }
        }
Exemplo n.º 43
0
        private static Bitmap ScaleBitmap(Bitmap image, int width, int height)
        {
            if (height == -1)
            {
                var scale = (double)image.Height / (double)image.Width;
                height = (int)Math.Ceiling(image.Height * ((double)width / (double)image.Width) * scale);
            }
            var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            // set the resolutions the same to avoid cropping due to resolution differences
            bmp.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            //use a graphics object to draw the resized image into the bitmap
            using (Graphics graphics = Graphics.FromImage(bmp))
            {
                //set the resize quality modes to high quality
                graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                //draw the image into the target bitmap
                graphics.DrawImage(image, 0, 0, bmp.Width, bmp.Height);
                bmp.MakeTransparent(bmp.GetPixel(0, 0));
            }
            //return the resulting bitmap
            return bmp;
        }
Exemplo n.º 44
0
        public Transformation(System.Drawing.Image image)
        {
            this.image = image;
            newImage   = new Bitmap(image.Width, image.Height);
            newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            graphics = Graphics.FromImage(newImage);
        }
Exemplo n.º 45
0
    private System.Drawing.Bitmap ResizeImage(System.Drawing.Bitmap ImagePath, int maxWidth, int maxHeight)
    {
        System.Drawing.Bitmap newImage = null;
        try
        {
            System.Drawing.Bitmap originalImage = ImagePath;// GetImageFromUrl(ImagePath);
            if (originalImage != null)
            {
                int    newWidth    = originalImage.Width;
                int    newHeight   = originalImage.Height;
                double aspectRatio = (double)originalImage.Width / (double)originalImage.Height;

                if (originalImage.Width > originalImage.Height)
                {
                    if (aspectRatio <= 1 && originalImage.Width > maxWidth)
                    {
                        newWidth  = maxWidth;
                        newHeight = (int)Math.Round(newWidth / aspectRatio);
                    }
                    else if (aspectRatio > 1 && originalImage.Height > maxHeight)
                    {
                        newHeight = maxHeight;
                        newWidth  = (int)Math.Round(newHeight * aspectRatio);
                    }
                }
                else
                {
                    if (aspectRatio <= 1 && originalImage.Height > maxHeight)
                    {
                        newHeight = maxHeight;
                        newWidth  = (int)Math.Round(newHeight * aspectRatio);
                    }
                    else if (aspectRatio > 1 && originalImage.Width > maxWidth)
                    {
                        newWidth  = maxWidth;
                        newHeight = (int)Math.Round(newWidth / aspectRatio);
                    }
                }
                newImage = new System.Drawing.Bitmap(originalImage, newWidth, newHeight);
                //newImage = new System.Drawing.Bitmap(originalImage, 40, 40);
                newImage.SetResolution((float)newWidth, (float)newHeight);
                System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(newImage);
                g.CompositingQuality = CompositingQuality.HighQuality;
                g.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                g.SmoothingMode      = SmoothingMode.HighQuality;
                g.DrawImage(originalImage, 0, 0, newImage.Width, newImage.Height);
                originalImage.Dispose();
                g.Dispose();
            }
        }
        catch (Exception ex)
        {
        }
        finally
        {
        }
        return(newImage);
    }
Exemplo n.º 46
0
 /// <summary>
 /// Creates a new, blank BitmapGdi with the specified width and height. The pixel format is fixed: 32bppArgb, aka Bgra32.
 /// </summary>
 public BitmapGdi(int width, int height)
 {
     Width  = width;
     Height = height;
     Stride = width * 4 + (16 - (width * 4) % 16) % 16; // pad to 16 bytes
     _bytes = new SharedPinnedByteArray(Stride * Height);
     Bitmap = new D.Bitmap(Width, Height, Stride, D.Imaging.PixelFormat.Format32bppArgb, _bytes.Address);
     Bitmap.SetResolution(96, 96);
 }
Exemplo n.º 47
0
        ResizeImageHeight(string imgPath, string saveTo, int resizeHeight)     //, int Width, int Height, int X, int Y)
        {
            try
            {
                using (var originalImage = sd.Image.FromFile(imgPath))
                {
                    var originalWidth  = int.Parse(originalImage.Width.ToString());
                    var originalHeight = int.Parse(originalImage.Height.ToString());

                    /*
                     * chia theo tỉ lể tìm ra chiều cao mới
                     * int originalImage_H -----------> resizeHeight
                     * int originalImage_W ----------->???NewWidth
                     *
                     */
                    var newWidth = originalWidth * resizeHeight / originalHeight;
                    using (var bmp = new sd.Bitmap(newWidth, resizeHeight)) //(Width, Height))
                    {
                        bmp.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
                        using (var graphic = sd.Graphics.FromImage(bmp))
                        {
                            graphic.SmoothingMode      = SmoothingMode.AntiAlias;
                            graphic.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                            graphic.PixelOffsetMode    = PixelOffsetMode.HighQuality;
                            graphic.CompositingQuality = CompositingQuality.HighQuality;
                            graphic.DrawImage(originalImage,
                                              new sd.Rectangle(0, 0, newWidth,
                                                               resizeHeight)); //, X, Y, Width, Height, sd.GraphicsUnit.Pixel);
                            var msBuffer = new MemoryStream();
                            bmp.Save(msBuffer, originalImage.RawFormat);
                            var bufferImage = msBuffer.GetBuffer();
                            msBuffer.Dispose();
                            using (var msWrite = new MemoryStream(bufferImage, 0, bufferImage.Length))
                            {
                                msWrite.Write(bufferImage, 0, bufferImage.Length);
                                using (var imageResized = sd.Image.FromStream(msWrite, true))
                                {
                                    //string saveTo = Server.MapPath("~/Images/imgCrop/") + "small" + ImageName;
                                    imageResized.Save(saveTo, imageResized.RawFormat);
                                }

                                msWrite.Dispose();
                            }

                            graphic.Dispose();
                        }

                        bmp.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Exemplo n.º 48
0
    //פונקציה שמשנה גודל לתמונות

    static System.Drawing.Image FixedSize(System.Drawing.Image imgPhoto, int Width, int Height)

    {
        int   sourceWidth  = Convert.ToInt32(imgPhoto.Width);
        int   sourceHeight = Convert.ToInt32(imgPhoto.Height);
        int   sourceX      = 0;
        int   sourceY      = 0;
        int   destX        = 0;
        int   destY        = 0;
        float nPercent     = 0;
        float nPercentW    = 0;
        float nPercentH    = 0;

        nPercentW = ((float)Width / (float)sourceWidth);
        nPercentH = ((float)Height / (float)sourceHeight);
        if (nPercentH < nPercentW)
        {
            nPercent = nPercentH;
            destX    = System.Convert.ToInt16((Width - (sourceWidth * nPercent)) / 2);
        }

        else
        {
            nPercent = nPercentW;

            destY = System.Convert.ToInt16((Height - (sourceHeight * nPercent)) / 2);
        }


        int destWidth  = (int)(sourceWidth * nPercent);
        int destHeight = (int)(sourceHeight * nPercent);

        System.Drawing.Bitmap bmPhoto = new System.Drawing.Bitmap(Width, Height, PixelFormat.Format24bppRgb);

        bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);

        System.Drawing.Graphics grPhoto = System.Drawing.Graphics.FromImage(bmPhoto);

        grPhoto.Clear(System.Drawing.Color.White);

        grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;


        grPhoto.DrawImage(imgPhoto,

                          new System.Drawing.Rectangle(destX, destY, destWidth, destHeight),

                          new System.Drawing.Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),

                          System.Drawing.GraphicsUnit.Pixel);


        grPhoto.Dispose();

        return(bmPhoto);
    }
Exemplo n.º 49
0
        protected void btnCrop_Click(object sender, EventArgs e)
        {
            int X1 = Convert.ToInt32(Request.Form["x1"]);
            int Y1 = Convert.ToInt32(Request["y1"]);
            int X2 = Convert.ToInt32(Request.Form["x2"]);
            int Y2 = Convert.ToInt32(Request.Form["y2"]);
            int X  = System.Math.Min(X1, X2);
            int Y  = System.Math.Min(Y1, Y2);
            int w  = Convert.ToInt32(Request.Form["w"]);
            int h  = Convert.ToInt32(Request.Form["h"]);

            // That can be any image type (jpg,jpeg,png,gif) from any where in the local server
            string originalFile = Server.MapPath("~/images/02.jpg");


            using (System.Drawing.Image img = System.Drawing.Image.FromFile(originalFile))
            {
                using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(w, h))
                {
                    _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                    using (Graphics _graphic = Graphics.FromImage(_bitmap))
                    {
                        _graphic.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        _graphic.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        _graphic.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                        _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        _graphic.DrawImage(img, 0, 0, w, h);
                        _graphic.DrawImage(img, new Rectangle(0, 0, w, h), X, Y, w, h, GraphicsUnit.Pixel);

                        string extension       = Path.GetExtension(originalFile);
                        string croppedFileName = Guid.NewGuid().ToString();
                        string path            = Server.MapPath("~/cropped/");


                        // If the image is a gif file, change it into png
                        if (extension.EndsWith("gif", StringComparison.OrdinalIgnoreCase))
                        {
                            extension = ".png";
                        }

                        string newFullPathName = string.Concat(path, croppedFileName, extension);

                        using (EncoderParameters encoderParameters = new EncoderParameters(1))
                        {
                            encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                            _bitmap.Save(newFullPathName, GetImageCodec(extension), encoderParameters);
                        }

                        lblCroppedImage.Text = string.Format("<img src='cropped/{0}' alt='Cropped image'>", croppedFileName + extension);
                    }
                }
            }
        }
Exemplo n.º 50
0
        public string GetFile(int ImageId, int size)
        {
            try
            {
                System.Drawing.Image imNormal = System.Drawing.Image.FromFile(GetServerPath("/Content/Content-image/" + ImageId + ".jpg"));
                System.Drawing.Image iii;

                Double xRatio    = (double)imNormal.Width / size;
                Double yRatio    = (double)imNormal.Height / size;
                Double ratio     = Math.Max(xRatio, yRatio);
                int    nnx       = (int)Math.Floor(imNormal.Width / ratio);
                int    nny       = (int)Math.Floor(imNormal.Height / ratio);
                var    destRect  = new System.Drawing.Rectangle(0, 0, nnx, nny);
                var    destImage = new System.Drawing.Bitmap(nnx, nny);
                destImage.SetResolution(imNormal.HorizontalResolution, imNormal.VerticalResolution);
                using (var grapgics = System.Drawing.Graphics.FromImage(destImage))
                {
                    grapgics.CompositingMode    = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
                    grapgics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                    grapgics.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    grapgics.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    grapgics.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

                    using (var wrapMode = new System.Drawing.Imaging.ImageAttributes())
                    {
                        wrapMode.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY);
                        grapgics.DrawImage(imNormal, destRect, 0, 0, imNormal.Width, imNormal.Height, System.Drawing.GraphicsUnit.Pixel, wrapMode);
                    }
                }
                iii = destImage;

                string name = "Raccoonogram_im_" + ImageId + "_" + size + "_" + DateTime.Now;
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                using (System.Security.Cryptography.MD5 md5hash = System.Security.Cryptography.MD5.Create())
                {
                    byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(name);
                    byte[] hash       = md5hash.ComputeHash(inputBytes);
                    for (int i = 0; i < hash.Length; i++)
                    {
                        sb.Append(hash[i].ToString("X2"));
                    }
                }

                string file_name = System.Web.Hosting.HostingEnvironment.MapPath("~/Content/downloads/") + sb.ToString() + ".jpg";
                iii.Save(file_name);
                return(sb.ToString());
            }
            catch (Exception ex)
            {
                return(ex.ToString());
            }
        }
Exemplo n.º 51
0
        public void Resize(Bitmap src, Bitmap dst, object options = null)
        {
            var mode = InterpolationMode.HighQualityBicubic;

            if (options != null)
            {
                if (options is InterpolationMode m)
                {
                    mode = m;
                }
                else
                {
                    throw new ArgumentException("Bad option.");
                }
            }

            // // run through scaler
            // var bitmap = new System.Drawing.Bitmap(dst.Width, dst.Height, GetSystemPixelFormat(dst));
            // using (var graphics = Graphics.FromImage(bitmap)) {
            //
            //   graphics.CompositingQuality = CompositingQuality.HighQuality;
            //   graphics.InterpolationMode = mode;
            //   graphics.SmoothingMode = SmoothingMode.HighQuality;
            //
            //   var srcBitmap = ToSystemBitmap(src);
            //
            //   graphics.DrawImage(srcBitmap, -1, -1, srcBitmap.Width + 1, srcBitmap.Height + 1);
            // }

            var destRect   = new Rectangle(0, 0, dst.Width, dst.Height);
            var destBitmap = new System.Drawing.Bitmap(dst.Width, dst.Height, GetSystemPixelFormat(dst));
            var srcBitmap  = ToSystemBitmap(src);

            destBitmap.SetResolution(96, 96);

            using (var graphics = Graphics.FromImage(destBitmap)) {
                graphics.CompositingMode    = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode  = mode;
                graphics.SmoothingMode      = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode    = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes()) {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(srcBitmap, destRect, 0, 0, srcBitmap.Width, srcBitmap.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            FromSystemBitmap(destBitmap, dst);
            srcBitmap.Dispose();
            destBitmap.Dispose();
        }
Exemplo n.º 52
0
        /// <summary>
        /// Modifies an image image.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <param name="w">The w.</param>
        /// <param name="h">The h.</param>
        /// <param name="modType">Type of the mod. Crop or Resize</param>
        /// <param name="url"> </param>
        /// <returns>New Image Id</returns>
        private string ModifyImage(float x, float y, float w, float h, ImageModificationType modType, string url)
        {
            //   ModifiedImageId = Guid.NewGuid();
            string finalUrl = "";
            Image  img      = new Bitmap(url);//ImageHelper.ByteArrayToImage();//WorkingImage);

            using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap((int)w, (int)h))
            {
                _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                using (Graphics _graphic = Graphics.FromImage(_bitmap))
                {
                    _graphic.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    _graphic.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    _graphic.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                    if (modType == ImageModificationType.Crop)
                    {
                        _graphic.DrawImage(img, 0, 0, w, h);
                        _graphic.DrawImage(img, new Rectangle(0, 0, (int)w, (int)h), x, y, w, h, GraphicsUnit.Pixel);
                    }
                    else if (modType == ImageModificationType.Resize)
                    {
                        _graphic.DrawImage(img, 0, 0, img.Width, img.Height);
                        _graphic.DrawImage(img, new Rectangle(0, 0, W_FixedSize, H_FixedSize), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
                    }

                    string extension = Path.GetExtension(url);// WorkingImageExtension;

                    // If the image is a gif file, change it into png
                    if (extension.EndsWith("gif", StringComparison.OrdinalIgnoreCase))
                    {
                        extension = ".png";
                    }

                    using (EncoderParameters encoderParameters = new EncoderParameters(1))
                    {
                        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
                        finalUrl = Path.GetDirectoryName(url) + "/" + Path.GetFileNameWithoutExtension(url) + "-Crop-" + x + "-" + y + "-" + w + "-" + h +
                                   extension;
                        _bitmap.Save(finalUrl, ImageHelper.GetImageFormat(extension));

                        finalUrl = finalUrl.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);
                        //  ModifiedImage = ImageHelper.ImageToByteArray(_bitmap, extension, encoderParameters);
                    }
                }
            }

            return(finalUrl);
        }
Exemplo n.º 53
0
        /// <summary>
        /// Scales an image and keeps the aspect ratio
        /// </summary>
        /// <param name="bitmap">The bitmap to scale</param>
        /// <param name="width">The canvas width</param>
        /// <param name="height">The canvas height</param>
        /// <returns>A scaled bitmap with a maintained aspect ratio</returns>
        public GDI.Bitmap ScaleBitmap(GDI.Bitmap bitmap, int width, int height)
        {
            // If the bitmap is empty, return null
            if (bitmap == null)
            {
                return(null);
            }

            GDI.Rectangle src  = new GDI.Rectangle(GDI.Point.Empty, bitmap.Size);
            GDI.Rectangle dest = GDI.Rectangle.Empty;

            float ratio       = 0;
            float widthRatio  = (float)width / (float)src.Width;
            float heightRatio = (float)height / (float)src.Height;

            // If the height is less than the width
            if (heightRatio < widthRatio)
            {
                ratio  = heightRatio;
                dest.X = (int)((width - (src.Width * ratio)) / 2);
            }
            else
            {
                ratio  = widthRatio;
                dest.Y = (int)((height - (src.Height * ratio)) / 2);
            }

            // Set destination size
            dest.Width  = (int)(src.Width * ratio) == 0 ? 1 : (int)(src.Width * ratio);
            dest.Height = (int)(src.Height * ratio) == 0 ? 1 : (int)(src.Height * ratio);

            // Create a new scaled image
            GDI.Bitmap scaledImage = new GDI.Bitmap(width, height, PixelFormat.Format32bppArgb);

            // Create a graphics context to draw the scaled image
            using (GDI.Graphics gfx = GDI.Graphics.FromImage(scaledImage))
            {
                // Set image resolution
                scaledImage.SetResolution(gfx.DpiX, gfx.DpiY);

                // Create the scaled image
                gfx.InterpolationMode = InterpolationMode.Low;
                gfx.SmoothingMode     = SmoothingMode.None;
                gfx.DrawImage(bitmap, dest, src, GDI.GraphicsUnit.Pixel);
            }

            // Dispose of original bitmap, return scaled bitmap
            bitmap.Dispose();
            return(scaledImage);
        }
Exemplo n.º 54
0
        /// <summary>
        /// Crops
        /// </summary>
        /// <param name="originalFile"></param>
        /// <param name="w"></param>
        /// <param name="h"></param>
        /// <param name="X"></param>
        /// <param name="Y"></param>
        /// <returns></returns>
        public static string BasCropImage(string originalFilePath, int w, int h, int X, int Y, string serverPathToSave,
                                          string croppedFileName, bool resizeImage, int newWidth, int newHeight)
        {
            using (System.Drawing.Image img = System.Drawing.Image.FromFile(originalFilePath))
            {
                using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(w, h))
                {
                    _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                    using (Graphics _graphic = Graphics.FromImage(_bitmap))
                    {
                        _graphic.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        _graphic.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        _graphic.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                        _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        //_graphic.drDrawImage(img, 0, 0, w, h);
                        _graphic.DrawImage(img, new Rectangle(0, 0, w, h), X, Y, w, h, GraphicsUnit.Pixel);

                        string extension = Path.GetExtension(originalFilePath);
                        // If the image is a gif file, change it into png
                        if (extension.EndsWith("gif", StringComparison.OrdinalIgnoreCase))
                        {
                            extension = ".png";
                        }

                        string newFullPathName = string.Concat(serverPathToSave, croppedFileName, extension);

                        using (EncoderParameters encoderParameters = new EncoderParameters(1))
                        {
                            encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
                            if (resizeImage)
                            {
                                ResizeAndSaveBitmap(_bitmap, newWidth, newHeight, newFullPathName);
                            }
                            else
                            {
                                _bitmap.Save(newFullPathName, GetImageCodec(extension), encoderParameters);
                            }
                        }

                        //// Saving the resized thumbnail of the original cropped image
                        //var thumbPath = ConversionHelper.GetSafeServerMapPath(Path.Combine(SystemSettings.PostImageThumbnailPath,
                        //    croppedFileName + extension));
                        //FileSaveHelper.ResizeAndSaveFromImagePath(newFullPathName, 99, 51, thumbPath);

                        return(croppedFileName + extension);
                    }
                }
            }
        }
Exemplo n.º 55
0
        private Bitmap CreateObjectBitmap()
        {
            float dpiX = 200F;
            float dpiY = 200F;

            Bitmap bm = new System.Drawing.Bitmap(
                Convert.ToInt32(r.ReportDefinition.PageWidth.Size / 2540F * dpiX),
                Convert.ToInt32(r.ReportDefinition.PageHeight.Size / 2540F * dpiY)
                );

            bm.MakeTransparent(Color.White);
            bm.SetResolution(dpiX, dpiY);

            return(bm);
        }
Exemplo n.º 56
0
        public static void EditSize(string OrgFileName, string DesFileName, int WidthLimit, int HeightLimit)
        {
            if (System.IO.File.Exists(Path.Combine(DesFileName)))
            {
                System.IO.File.Delete(Path.Combine(DesFileName));
            }

            ImageFormat Format;

            System.Drawing.Image OrgImg = System.Drawing.Image.FromFile(OrgFileName);
            int    DesWidth             = OrgImg.Width;
            int    DesHeight            = OrgImg.Height;
            double ratio = (double)DesWidth / (double)DesHeight;

            Format = OrgImg.RawFormat;
            if (DesWidth <= WidthLimit && DesHeight <= HeightLimit)
            {
                File.Copy(OrgFileName, DesFileName);
                return;
            }

            if (DesWidth > WidthLimit)
            {
                DesWidth  = WidthLimit;
                DesHeight = (int)Math.Round(DesWidth / ratio);
            }

            if (DesHeight > HeightLimit)
            {
                DesHeight = HeightLimit;
                DesWidth  = (int)Math.Round(DesHeight * ratio);
            }

            Bitmap DesImg = new System.Drawing.Bitmap(DesWidth, DesHeight, PixelFormat.Format24bppRgb);

            DesImg.SetResolution(96, 96);

            Graphics GraphicImg = Graphics.FromImage(DesImg);

            GraphicImg.SmoothingMode     = SmoothingMode.AntiAlias;
            GraphicImg.InterpolationMode = InterpolationMode.HighQualityBicubic;
            GraphicImg.PixelOffsetMode   = PixelOffsetMode.HighQuality;
            System.Drawing.Rectangle oRectangle = new Rectangle(0, 0, DesWidth, DesHeight);
            GraphicImg.DrawImage(OrgImg, oRectangle);
            OrgImg.Dispose();
            DesImg.Save(DesFileName, Format);
        }
Exemplo n.º 57
0
        /// <summary>
        /// Modifies an Profile image.
        /// </summary>
        /// <param name="x">The x.</param>
        /// <param name="y">The y.</param>
        /// <param name="w">The w.</param>
        /// <param name="h">The h.</param>
        /// <param name="PersonID">Profile Image to work on</param>
        /// <returns>New Image Id</returns>
        private bool ModifyImage(int x, int y, int w, int h, Person person)
        {
            string ProfilDirSetting = ConfigurationManager.AppSettings["ProfileImage"];

            if (string.IsNullOrWhiteSpace(ProfilDirSetting))
            {
                throw new ArgumentNullException();
            }

            var ProfilBilled = string.Format(ProfilDirSetting, person.PersonID);

            if (System.IO.File.Exists(Server.MapPath(ProfilBilled)))
            {
                Image img = Image.FromFile(Server.MapPath(ProfilBilled));



                using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(428, 550))
                {
                    _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                    using (Graphics _graphic = Graphics.FromImage(_bitmap))
                    {
                        _graphic.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        _graphic.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                        _graphic.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                        _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                        _graphic.Clear(Color.White);
                        //_graphic.DrawImage(img, 0, 0, w, h);
                        _graphic.DrawImage(img, new Rectangle(0, 0, 428, 550), x, y, w, h, GraphicsUnit.Pixel);
                        //_graphic.DrawImage(img, new Rectangle(0, 0, w, h), x, y, w, h, GraphicsUnit.Pixel);
                        //_graphic.DrawImage(img, 0, 0, img.Width, img.Height);
                        //_graphic.DrawImage(img, new Rectangle(0, 0, 428, 550), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
                    }
                    System.Drawing.Imaging.PropertyItem prop = img.PropertyItems[0];
                    SetProperty(ref prop, 270, string.Format("Username: {0}, {1}", person.UserName, person.FullName));
                    _bitmap.SetPropertyItem(prop);
                    SetProperty(ref prop, 33432, "Copyright Natteravnene www.natteravnene.dk");
                    _bitmap.SetPropertyItem(prop);
                    //TODO: Set more properties
                    img.Dispose();

                    _bitmap.Save(Server.MapPath(ProfilBilled), System.Drawing.Imaging.ImageFormat.Jpeg);
                }
            }

            return(true);
        }
Exemplo n.º 58
0
        /// <summary>
        /// Creates an Image with a Glass Table effect
        /// </summary>
        /// <param name="_Image">Original image</param>
        /// <param name="_BackgroundColor">New image background color</param>
        /// <param name="_Reflectivity">Reflectivity (0 to 255)</param>
        public static Image DrawReflection(Image Image, Color BackColor, int Reflectivity)
        {
            if (Reflectivity > 255)
            {
                Reflectivity = 255;
            }

            // Calculate the size of the new image
            int height = (int)(Image.Height + (Image.Height * ((float)Reflectivity / 255)));

            System.Drawing.Bitmap newImage = new System.Drawing.Bitmap(Image.Width, height, PixelFormat.Format24bppRgb);
            newImage.SetResolution(Image.HorizontalResolution, Image.VerticalResolution);

            using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(newImage))
            {
                // Initialize main graphics buffer
                graphics.Clear(BackColor);
                graphics.DrawImage(Image, new Point(0, 0));
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                Rectangle destinationRectangle = new Rectangle(0, Image.Size.Height, Image.Size.Width, Image.Size.Height);

                // Prepare the reflected image
                int   reflectionHeight = (Image.Height * Reflectivity) / 255;
                Image reflectedImage   = new System.Drawing.Bitmap(Image.Width, reflectionHeight);

                // Draw just the reflection on a second graphics buffer
                using (System.Drawing.Graphics gReflection = System.Drawing.Graphics.FromImage(reflectedImage))
                {
                    gReflection.DrawImage(Image, new Rectangle(0, 0, reflectedImage.Width, reflectedImage.Height),
                                          0, Image.Height - reflectedImage.Height, reflectedImage.Width, reflectedImage.Height, GraphicsUnit.Pixel);
                }
                reflectedImage.RotateFlip(RotateFlipType.RotateNoneFlipY);
                Rectangle imageRectangle = new Rectangle(destinationRectangle.X, destinationRectangle.Y,
                                                         destinationRectangle.Width, (destinationRectangle.Height * Reflectivity) / 255);

                // Draw the image on the original graphics
                graphics.DrawImage(reflectedImage, imageRectangle);

                // Finish the reflection using a gradiend brush
                LinearGradientBrush brush = new LinearGradientBrush(imageRectangle,
                                                                    Color.FromArgb(255 - Reflectivity, BackColor),
                                                                    BackColor, 90, false);
                graphics.FillRectangle(brush, imageRectangle);
            }

            return(newImage);
        }
Exemplo n.º 59
0
        private static string ModifyImageByFile(int x, int y, int w, int h, ImageModificationType modType, Image img, string filePath, string ext)
        {
            //Image img = Image.FromFile(IMGToModifypath);

            var WorkingImageExtension = img.RawFormat.ToString();//Path.GetExtension(IMGToModifypath);

            using (System.Drawing.Bitmap _bitmap = new System.Drawing.Bitmap(w, h))
            {
                _bitmap.SetResolution(img.HorizontalResolution, img.VerticalResolution);
                using (Graphics _graphic = Graphics.FromImage(_bitmap))
                {
                    _graphic.InterpolationMode  = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    _graphic.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    _graphic.PixelOffsetMode    = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    _graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                    if (modType == ImageModificationType.Crop)
                    {
                        _graphic.DrawImage(img, 0, 0, w, h);
                        _graphic.DrawImage(img, new Rectangle(0, 0, w, h), x, y, w, h, GraphicsUnit.Pixel);
                    }
                    else if (modType == ImageModificationType.Resize)
                    {
                        _graphic.DrawImage(img, 0, 0, img.Width, img.Height);
                        _graphic.DrawImage(img, new Rectangle(0, 0, w, h), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel);
                    }

                    string extension = ext;

                    // If the image is a gif file, change it into png
                    if (extension.EndsWith("gif", StringComparison.OrdinalIgnoreCase))
                    {
                        extension = ".png";
                    }

                    using (EncoderParameters encoderParameters = new EncoderParameters(1))
                    {
                        encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 40L);
                        img.Dispose();
                        ImageSave(filePath, _bitmap, extension, encoderParameters);
                    }
                }
            }

            return("Successful");
        }
Exemplo n.º 60
0
        private Bitmap ProcessImage(Stream Source, int cw, int ch)
        {
            System.Drawing.Bitmap im = new System.Drawing.Bitmap(Source);

            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            im.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            stream.Close();
            stream.Dispose();

            int height = 0, width = 0;

            if (ch >= im.Height)
            {
                height = im.Height; width = im.Width;
            }
            else
            {
                height = ch; width = (int)((float)height * ((float)im.Width / im.Height));
            }
            if (cw < width)
            {
                height = cw * height / width; width = cw;
            }

            System.Drawing.Bitmap thumb = new System.Drawing.Bitmap(width, height, im.PixelFormat);
            thumb.MakeTransparent(Color.White);
            thumb.SetResolution(im.HorizontalResolution, im.VerticalResolution);
            Graphics gThumb             = Graphics.FromImage(thumb);

            gThumb.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear;
            gThumb.SmoothingMode     = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
            gThumb.PixelOffsetMode   = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

            gThumb.DrawImage(im, -1, -1, width + 1, height + 1);
            gThumb.Dispose();

            System.IO.MemoryStream streamThumb = new System.IO.MemoryStream();
            thumb.Save(streamThumb, System.Drawing.Imaging.ImageFormat.Jpeg);

            im.Dispose();
            streamThumb.Close();
            streamThumb.Dispose();
            System.GC.Collect();

            return(thumb);
        }