public static Bitmap Get(Image image, int maxWidth, int maxHeight) { if (image.Width < maxWidth && image.Height < maxHeight) { maxWidth = image.Width; maxHeight = image.Height; } var widthScaleFactor = (float)maxWidth / image.Width; var heightScaleFactor = (float)maxHeight / image.Height; var scaleFactor = widthScaleFactor > heightScaleFactor ? heightScaleFactor : widthScaleFactor; var width = Convert.ToInt32(scaleFactor * image.Width); var height = Convert.ToInt32(scaleFactor * image.Height); var bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb); bitmap.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (var graphics = Graphics.FromImage(bitmap)) { graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.CompositingMode = CompositingMode.SourceCopy; var imageAttributes = new ImageAttributes(); imageAttributes.SetWrapMode(WrapMode.TileFlipXY); var destRectangle = new Rectangle(0, 0, width, height); graphics.DrawImage(image, destRectangle, 0, 0, width, height, GraphicsUnit.Pixel, imageAttributes); } return bitmap; }
/// <summary> /// Loads an image from path into a byte array. /// </summary> public static byte[] LoadImage(string path) { var image = Image.FromFile(path); var destinationRectangle = new Rectangle(0, 0, TargetWidth, TargetHeight); var destinationImage = new Bitmap(TargetWidth, TargetHeight); destinationImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (var graphics = Graphics.FromImage(image)) { 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, destinationRectangle, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); } } byte[] buffer; using (var stream = new MemoryStream()) { image.Save(stream, ImageFormat.Png); buffer = stream.ToArray(); } return buffer; }
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; }
/// <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; }
/// <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; }
public static Bitmap ResizeImage(Image image, System.Drawing.Size newSize) { // Make a rectangle that is the new size Rectangle destRect = new Rectangle(0, 0, newSize.Width, newSize.Height); // Make a bitmap that is the new size Bitmap destImage = new Bitmap(newSize.Width, newSize.Height); // Set new image to the resolution of the original destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); // Create a GDI holder and use it using (Graphics graphics = Graphics.FromImage(destImage)) { // Set our quality options graphics.CompositingMode = CompositingMode.SourceCopy; graphics.CompositingQuality = CompositingQuality.HighQuality; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.SmoothingMode = SmoothingMode.HighQuality; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; // Resize original image into new one using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); } } return destImage; }
/// <summary> /// 创建缩略图 /// </summary> public void cutAvatar(string imgSrc, int x, int y, int width, int height, long Quality, string SavePath, int t) { Image original = Image.FromFile(imgSrc); Bitmap img = new Bitmap(t, t, PixelFormat.Format24bppRgb); img.MakeTransparent(img.GetPixel(0, 0)); img.SetResolution(72, 72); using (Graphics gr = Graphics.FromImage(img)) { if (original.RawFormat.Equals(ImageFormat.Jpeg) || original.RawFormat.Equals(ImageFormat.Png) || original.RawFormat.Equals(ImageFormat.Bmp)) { gr.Clear(Color.Transparent); } if (original.RawFormat.Equals(ImageFormat.Gif)) { gr.Clear(Color.White); } gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.SmoothingMode = SmoothingMode.AntiAlias; gr.CompositingQuality = CompositingQuality.HighQuality; gr.PixelOffsetMode = PixelOffsetMode.HighQuality; gr.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; using (var attribute = new System.Drawing.Imaging.ImageAttributes()) { attribute.SetWrapMode(WrapMode.TileFlipXY); gr.DrawImage(original, new Rectangle(0, 0, t, t), x, y, width, height, GraphicsUnit.Pixel, attribute); } } ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg"); if (original.RawFormat.Equals(ImageFormat.Jpeg)) { myImageCodecInfo = GetEncoderInfo("image/jpeg"); } else if (original.RawFormat.Equals(ImageFormat.Png)) { myImageCodecInfo = GetEncoderInfo("image/png"); } else if (original.RawFormat.Equals(ImageFormat.Gif)) { myImageCodecInfo = GetEncoderInfo("image/gif"); } else if (original.RawFormat.Equals(ImageFormat.Bmp)) { myImageCodecInfo = GetEncoderInfo("image/bmp"); } Encoder myEncoder = Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, Quality); myEncoderParameters.Param[0] = myEncoderParameter; img.Save(SavePath, myImageCodecInfo, myEncoderParameters); }
//Метод для высококачественного изменения размера изображения 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; }
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; }
public static Bitmap ResizeBitmap(Bitmap bmp, int width, int height) { if (width == 0 || height == 0) { return(bmp); } Rectangle destRect = new Rectangle(0, 0, width, height); Bitmap destBmp = new Bitmap(width, height); using (Graphics gfx = Graphics.FromImage(destBmp)) { gfx.CompositingMode = CompositingMode.SourceCopy; gfx.CompositingQuality = CompositingQuality.HighQuality; gfx.InterpolationMode = InterpolationMode.HighQualityBicubic; gfx.SmoothingMode = SmoothingMode.HighQuality; gfx.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new System.Drawing.Imaging.ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.Tile); gfx.DrawImage(bmp, destRect, 0, 0, bmp.Width, bmp.Height, GraphicsUnit.Pixel, wrapMode); } } return(destBmp); }
public static void DrawBackgroundImage(Graphics g, Image backgroundImage, Color backColor, ImageLayout backgroundImageLayout, Rectangle bounds, Rectangle clipRect, Point scrollOffset, RightToLeft rightToLeft) { if (g == null) { throw new ArgumentNullException("g"); } if (backgroundImageLayout == ImageLayout.Tile) { using (TextureBrush brush = new TextureBrush(backgroundImage, WrapMode.Tile)) { if (scrollOffset != Point.Empty) { Matrix transform = brush.Transform; transform.Translate((float) scrollOffset.X, (float) scrollOffset.Y); brush.Transform = transform; } g.FillRectangle(brush, clipRect); return; } } Rectangle rect = CalculateBackgroundImageRectangle(bounds, backgroundImage, backgroundImageLayout); if ((rightToLeft == RightToLeft.Yes) && (backgroundImageLayout == ImageLayout.None)) { rect.X += clipRect.Width - rect.Width; } using (SolidBrush brush2 = new SolidBrush(backColor)) { g.FillRectangle(brush2, clipRect); } if (!clipRect.Contains(rect)) { if ((backgroundImageLayout == ImageLayout.Stretch) || (backgroundImageLayout == ImageLayout.Zoom)) { rect.Intersect(clipRect); g.DrawImage(backgroundImage, rect); } else if (backgroundImageLayout == ImageLayout.None) { rect.Offset(clipRect.Location); Rectangle destRect = rect; destRect.Intersect(clipRect); Rectangle rectangle3 = new Rectangle(Point.Empty, destRect.Size); g.DrawImage(backgroundImage, destRect, rectangle3.X, rectangle3.Y, rectangle3.Width, rectangle3.Height, GraphicsUnit.Pixel); } else { Rectangle rectangle4 = rect; rectangle4.Intersect(clipRect); Rectangle rectangle5 = new Rectangle(new Point(rectangle4.X - rect.X, rectangle4.Y - rect.Y), rectangle4.Size); g.DrawImage(backgroundImage, rectangle4, rectangle5.X, rectangle5.Y, rectangle5.Width, rectangle5.Height, GraphicsUnit.Pixel); } } else { ImageAttributes imageAttr = new ImageAttributes(); imageAttr.SetWrapMode(WrapMode.TileFlipXY); g.DrawImage(backgroundImage, rect, 0, 0, backgroundImage.Width, backgroundImage.Height, GraphicsUnit.Pixel, imageAttr); imageAttr.Dispose(); } }
public static Bitmap ResizeImage(Image image, int width, int height) { 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); graphics.Dispose(); } } return destImage; }
/// <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 Rectangle(0, 0, width, height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes); } return newImg; }
/// <summary> /// Converts a bitmap to grayscale. Based on: /// http://tech.pro/tutorial/660/csharp-tutorial-convert-a-color-image-to-grayscale /// </summary> public static Bitmap MakeGrayscale(this Bitmap original, int newWidth, int newHeight) { // Create a blank bitmap the desired size Bitmap newBitmap = new Bitmap(newWidth, newHeight); using (Graphics g = Graphics.FromImage(newBitmap)) { // Create the grayscale ColorMatrix ColorMatrix colorMatrix = new ColorMatrix(new float[][] { new float[] { .3f, .3f, .3f, 0, 0 }, new float[] { .59f, .59f, .59f, 0, 0 }, new float[] { .11f, .11f, .11f, 0, 0 }, new float[] { 0, 0, 0, 1, 0 }, new float[] { 0, 0, 0, 0, 1 } }); ImageAttributes attributes = new ImageAttributes(); // Set the color matrix attribute attributes.SetColorMatrix(colorMatrix); // Fixes "ringing" around the borders... attributes.SetWrapMode(WrapMode.TileFlipXY); // Draw the original image on the new image using the grayscale color matrix g.CompositingMode = CompositingMode.SourceCopy; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.DrawImage(original, new Rectangle(0, 0, newWidth, newHeight), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); } return newBitmap; }
private static Bitmap ResizeImage(Image image, int width, int height) { if ((image == null) || (width <= 0) || (height <= 0)) { Logging.LogNullError(nameof(image) + " || " + nameof(width) + " || " + nameof(height)); return null; } Rectangle destRect = new Rectangle(0, 0, width, height); Bitmap destImage = new Bitmap(width, height); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (Graphics 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 (ImageAttributes wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); } } return destImage; }
/// <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; }
/// <summary> /// Looks for the brightest pixel after applying a redness filter. Narrows search first using a resampled copy of the image to eliminate edge dots. /// Expects an image that is already cropped to the interested area for faster processing. /// </summary> /// <param name="img"></param> /// <param name="mouse"></param> /// <param name="maxDistanceFromMouse"></param> /// <returns></returns> public unsafe Point FindMaxPixel(UnmanagedImage img, PointF mouse, float maxDistanceFromMouse) { int width = 15; int height = (int)Math.Ceiling((double)img.Height / (double)img.Width * width); if (width <= img.Width && height <= img.Height + 1) { width = img.Width; height = img.Height; } double scale = (double)img.Width / (double)width; UnmanagedImage lowRed = null; try { if (width != img.Width && height != img.Height) { using (Bitmap reduced = new Bitmap(width, height, PixelFormat.Format24bppRgb)) using (Graphics g = Graphics.FromImage(reduced)) using (ImageAttributes ia = new ImageAttributes()) { g.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; ia.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY); g.DrawImage(img.ToManagedImage(false), new Rectangle(0, 0, width, height), 0, 0, img.Width, img.Height, GraphicsUnit.Pixel, ia); //TODO: Not sure if ToManagedImage will stick around after the underying image is disposed. I know that the bitmap data will be gone, guess that's most of it. using (UnmanagedImage rui = UnmanagedImage.FromManagedImage(reduced)) { lowRed = new RedEyeFilter(2).Apply(rui); // Make an copy using the red eye filter } } } else { //Don't resample unless needed lowRed = new RedEyeFilter(2).Apply(img); } Point max = GetMax(lowRed, new PointF(mouse.X / (float)scale, mouse.Y / (float)scale), maxDistanceFromMouse / scale); //We weren't scaling things? OK, cool... if (scale == 0) return max; //Otherwise, let's get the unscaled pixel. //Calculate the rectangle surrounding the selected pixel, but in source coordinates. int tinySize = (int)Math.Ceiling(scale) + 1; Rectangle tinyArea = new Rectangle((int)Math.Floor(scale * (double)max.X), (int)Math.Floor(scale * (double)max.Y), tinySize, tinySize); if (tinyArea.Right >= img.Width) tinyArea.Width -= img.Width - tinyArea.Right + 1; if (tinyArea.Bottom >= img.Height) tinyArea.Height -= img.Height - tinyArea.Bottom + 1; //Filter it and look using (UnmanagedImage tiny = new Crop(tinyArea).Apply(img)) { using (UnmanagedImage tinyRed = new RedEyeFilter(2).Apply(tiny)) { max = GetMax(tinyRed); max.X += tinyArea.X; max.Y += tinyArea.Y; } } return max; } finally { if (lowRed != null) lowRed.Dispose(); } }
public static void Fill(Graphics g, Rectangle rect) { if (_texture == null) GeneratePattern(); System.Drawing.Imaging.ImageAttributes imgAttr = new System.Drawing.Imaging.ImageAttributes(); imgAttr.SetWrapMode(WrapMode.TileFlipXY); g.FillRectangle(_texture, rect); //new Rectangle(0, 0, bmpBg.Width, bmpBg.Height)); }
public static void Fill(Graphics g, Rectangle rect) { if (_texture == null) { GeneratePattern(); } System.Drawing.Imaging.ImageAttributes imgAttr = new System.Drawing.Imaging.ImageAttributes(); imgAttr.SetWrapMode(WrapMode.TileFlipXY); g.FillRectangle(_texture, rect); //new Rectangle(0, 0, bmpBg.Width, bmpBg.Height)); }
protected override void OnPaint(PaintEventArgs e) { if (active) { e.Graphics.DrawRectangle(pBorderActive, 0, 0, this.Width - 1, this.Height - 1); e.Graphics.DrawLine(pShadowActive, 1, 1, 1, this.Height - 3); e.Graphics.DrawLine(pShadowActive, 1, 1, this.Width - 3, 1); e.Graphics.DrawLine(pHighlightActive, this.Width - 2, 1, this.Width - 2, this.Height - 2); e.Graphics.DrawLine(pHighlightActive, 1, this.Height - 2, this.Width - 2, this.Height - 2); } else { e.Graphics.DrawRectangle((this.Enabled ? (this.Focused || hover ? pBorderFocus : pBorder) : pBorderDisabled), 0, 0, this.Width - 1, this.Height - 1); e.Graphics.DrawLine((this.Enabled ? (this.Focused || hover ? pHighlightFocus : Pens.White) : pHighlightDisabled), 1, 1, 1, this.Height - 2); e.Graphics.DrawLine((this.Enabled ? (this.Focused || hover ? pHighlightFocus : Pens.White) : pHighlightDisabled), 1, 1, this.Width - 2, 1); e.Graphics.DrawLine((this.Enabled ? (this.Focused || hover ? pShadowFocus : pShadow) : pShadowDisabled), this.Width - 2, 2, this.Width - 2, this.Height - 2); e.Graphics.DrawLine((this.Enabled ? (this.Focused || hover ? pShadowFocus : pShadow) : pShadowDisabled), 2, this.Height - 2, this.Width - 2, this.Height - 2); } //e.Graphics.FillRectangle((this.Enabled ? (hover ? tbButtonBackgroundHover : tbButtonBackground) : tbButtonBackgroundDisabled), 2, 2, this.Width - 4, this.Height - 4); using (ImageAttributes attribs = new ImageAttributes()) { attribs.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY); e.Graphics.DrawImage((this.Enabled ? (active ? Properties.Resources.ButtonBackgroundActive : (hover ? Properties.Resources.ButtonBackgroundHover : Properties.Resources.ButtonBackground)) : Properties.Resources.ButtonBackgroundDisabled), new Rectangle(2, 2, this.Width - 4, this.Height - 4), 0, 0, 1, Properties.Resources.ButtonBackground.Height, GraphicsUnit.Pixel, attribs); } //e.Graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy; /*e.Graphics.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.Half; e.Graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.NearestNeighbor; int matw = this.Width - 2, matx = this.Height - 4; for (int i = 2; i < matw; i++) e.Graphics.DrawImage((this.Enabled ? (hover ? Properties.Resources.ButtonBackgroundDisabled : Properties.Resources.ButtonBackground) : Properties.Resources.ButtonBackgroundDisabled), i, 2, 1, matx); */ if (this.Focused && !hover) { e.Graphics.FillRectangle(bFocus, 2, 2, this.Width - 4, 2); e.Graphics.FillRectangle(bFocus, 2, this.Height - 4, this.Width - 4, 2); e.Graphics.FillRectangle(bFocus, 2, 4, 2, this.Height - 8); e.Graphics.FillRectangle(bFocus, this.Width - 4, 4, 2, this.Height - 8); } e.Graphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit; TextRenderer.DrawText(e.Graphics, this.Text, this.Font, new Rectangle(0, 0, this.Width, this.Height), (this.Enabled ? Color.Black : cDisabled), (TextFormatFlags.HorizontalCenter | TextFormatFlags.VerticalCenter | TextFormatFlags.EndEllipsis)); }
private void ResetPaintImage() { if (PaintImage != null) { PaintImage.Dispose(); PaintImage = null; } if (Image != null && Image.Width > 0 && Image.Height > 0 && DrawRect.Width > 0 && DrawRect.Height > 0) { PaintImage = new Bitmap((int)DrawRect.Width, (int)DrawRect.Height); using (Graphics g = Graphics.FromImage(PaintImage)) { System.Drawing.Imaging.ImageAttributes ima = new System.Drawing.Imaging.ImageAttributes(); ColorMatrix cm = new ColorMatrix(); cm.Matrix33 = Opacity; ima.SetColorMatrix(cm); Point pt = Point.Empty; switch (FillMode) { case ImageFillMode.Center: pt = new Point((int)(DrawRect.Width - Image.Width) / 2, (int)(DrawRect.Height - Image.Height) / 2); g.DrawImage(Image, new Rectangle(pt, Image.Size), 0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel, ima); break; case ImageFillMode.Strength: g.DrawImage(Image, Rectangle.Round(DrawRect), 0, 0, Image.Width, Image.Height, GraphicsUnit.Pixel, ima); break; case ImageFillMode.Title: ima.SetWrapMode(System.Drawing.Drawing2D.WrapMode.Tile); TextureBrush brush = new TextureBrush(Image, new Rectangle(0, 0, Image.Width, Image.Height), ima); g.FillRectangle(brush, DrawRect); break; case ImageFillMode.Zoom: float scale = 1; if (Image.Width > 0 && Image.Height > 0 && DrawRect.Width > 0 && DrawRect.Height > 0) { float f1 = DrawRect.Width / Image.Width; float f2 = DrawRect.Height / Image.Height; scale = f1 > f2 ? f2 : f1; float zWidth = scale * Image.Width; float zHeight = scale * Image.Height; //RectangleF zoomRect = new RectangleF( } break; } } } else { PaintImage = null; } }
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()); } }
public static void SquareCropAndResize(string inFile, Size newSize, string outFile) { using (Bitmap src = (Bitmap)Image.FromFile(inFile)) { Rectangle cropRect = new Rectangle(); if (src.Width > src.Height) { cropRect.X = (src.Width - src.Height) / 2; cropRect.Y = 0; cropRect.Width = src.Height; cropRect.Height = src.Height; } else { cropRect.X = 0; cropRect.Y = (src.Height - src.Width) / 2; cropRect.Width = src.Width; cropRect.Height = src.Width; } Rectangle resizeRect = new Rectangle(0, 0, newSize.Width, newSize.Height); using (Bitmap target = new Bitmap(resizeRect.Width, resizeRect.Height)) { target.SetResolution(src.HorizontalResolution, src.VerticalResolution); using (Graphics g = Graphics.FromImage(target)) { g.CompositingMode = CompositingMode.SourceCopy; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.CompositingQuality = CompositingQuality.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); g.DrawImage(src, resizeRect, cropRect.X, cropRect.Y, cropRect.Width, cropRect.Height, GraphicsUnit.Pixel, wrapMode); } g.Dispose(); } SaveToJpg(outFile, target, 90L); target.Dispose(); src.Dispose(); } } }
public object Create (Image image, float opacity) { var sdimage = new sd.Bitmap (image.ToSD ()); var att = new sdi.ImageAttributes (); att.SetWrapMode (sd2.WrapMode.Tile); if (opacity < 1.0f) { var colorMatrix = new sdi.ColorMatrix (new float[][] { new float [] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float [] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float [] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float [] { 0.0f, 0.0f, 0.0f, opacity, 0.0f }, new float [] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }); att.SetColorMatrix (colorMatrix); } return new sd.TextureBrush (sdimage, new sd.RectangleF (0, 0, sdimage.Width, sdimage.Height), att); }
/// <summary> /// Print /// </summary> /// <param name="printerName">Printer Name</param> public void Print(string printername) { if(PdfResult == 0) { try { PrinterSettings settings = new PrinterSettings(); settings.PrinterName = printername; settings.PrintToFile = false; //设置纸张大小(可以不设置取,取默认设置) //PaperSize ps = new PaperSize("Your Paper Name",595,842); //ps.RawKind = 9; //如果是自定义纸张,就要大于118, printer.PrinterSettings = settings; //图片拉伸 ImageAttributes ImgAtt = new ImageAttributes(); ImgAtt.SetWrapMode(WrapMode.TileFlipXY); //分页转换 int endPageNum = pdfFile.PageCount; Bitmap pageImage = null; for (int i = 0; i < endPageNum; i++) { pageImage = pdfFile.GetPageImage(i, 280); //pageImage.Save(i.ToString() + ".png",ImageFormat.Png); printer.PrintPage += delegate(object sender, PrintPageEventArgs e) { Graphics g = e.Graphics; g.InterpolationMode = InterpolationMode.HighQualityBicubic; //指定所绘制图像的位置和大小。将图像进行缩放以适合该矩形 //var dstRect = new Rectangle(20, 20, pageImage.Width/4 , pageImage.Height/4); Point[] points = {new Point(20, 20), new Point(pageImage.Width/4, 20), new Point(20, pageImage.Height/4)}; Point[] pointsA4 = {new Point(20, 20), new Point(575, 20), new Point(20, 822)}; //指定 image 对象中要绘制的部分 var imgRect = new Rectangle(0, 0, pageImage.Width , pageImage.Height); g.DrawImage(pageImage, pointsA4, imgRect, GraphicsUnit.Pixel, ImgAtt); }; printer.Print(); pageImage.Dispose(); } } catch(Exception ex) { Console.Write(ex.Message); PdfResult = 14; } } }
public static Image Resize(Image img, int srcX, int srcY, int srcWidth, int srcHeight, int dstWidth, int dstHeight) { var bmp = new Bitmap(dstWidth, dstHeight); using (var graphics = Graphics.FromImage(bmp)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.CompositingMode = CompositingMode.SourceCopy; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); var destRect = new Rectangle(0, 0, dstWidth, dstHeight); graphics.DrawImage(img, destRect, srcX, srcY, srcWidth, srcHeight, GraphicsUnit.Pixel, wrapMode); } } return bmp; }
public static Bitmap ResizeImage(Image image, Size size, bool killalfa, InterpolationMode interpolation) { if (image.Size == size) { return(new Bitmap((Image)image.Clone())); } Rectangle destRect = new Rectangle(0, 0, size.Width, size.Height); Bitmap destImage = new Bitmap(size.Width, size.Height); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (Graphics g = Graphics.FromImage(destImage)) { if (killalfa) { g.Clear(Color.White); } if (killalfa) { g.CompositingMode = CompositingMode.SourceOver; } else { g.CompositingMode = CompositingMode.SourceCopy; } g.CompositingQuality = CompositingQuality.HighQuality; g.SmoothingMode = SmoothingMode.HighQuality; g.InterpolationMode = interpolation; g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality; using (System.Drawing.Imaging.ImageAttributes wrapMode = new System.Drawing.Imaging.ImageAttributes()) { wrapMode.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY); g.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode); } } return(destImage); }
public static void DrawImageTiled(Graphics g, Image image, Rectangle destRect) { using (ImageAttributes attr = new ImageAttributes()) { // initialize wrap mode to tile attr.SetWrapMode(System.Drawing.Drawing2D.WrapMode.Tile); // create the texture brush using (TextureBrush b = new TextureBrush(image, new Rectangle(0, 0, image.Width, image.Height), attr)) { // adjust the origin of the brush to coincide with the destination rect b.TranslateTransform(destRect.Left, destRect.Top); // fill the area using the texture g.FillRectangle(b, destRect); } } }
public object Create(Image image, float opacity) { var sdimage = new sd.Bitmap(image.ToSD()); var att = new sdi.ImageAttributes(); att.SetWrapMode(sd2.WrapMode.Tile); if (opacity < 1.0f) { var colorMatrix = new sdi.ColorMatrix(new float[][] { new float [] { 1.0f, 0.0f, 0.0f, 0.0f, 0.0f }, new float [] { 0.0f, 1.0f, 0.0f, 0.0f, 0.0f }, new float [] { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f }, new float [] { 0.0f, 0.0f, 0.0f, opacity, 0.0f }, new float [] { 0.0f, 0.0f, 0.0f, 0.0f, 1.0f } }); att.SetColorMatrix(colorMatrix); } return(new sd.TextureBrush(sdimage, new sd.RectangleF(0, 0, sdimage.Width, sdimage.Height), att)); }
public static Image Crop(this Image img, int dstWidth, int dstHeight, int? startX = null, int? startY = null) { var bmp = new Bitmap(dstWidth, dstHeight); using (var graphics = Graphics.FromImage(bmp)) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.CompositingMode = CompositingMode.SourceCopy; graphics.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); var destRect = new Rectangle(0, 0, dstWidth, dstHeight); startX = startX.HasValue ? startX.Value : img.Width / 2; startY = startY.HasValue ? startY.Value : img.Height / 2; graphics.DrawImage(img, destRect, startX.Value, startY.Value, dstWidth, dstHeight, GraphicsUnit.Pixel, wrapMode); } } return bmp; }
// ------------------------------------------------------------------ /// <summary> /// Scale the given image to the given size. /// Uses a high interpolation mode quality. /// </summary> /// <param name="image">The image.</param> /// <param name="width">The width.</param> /// <param name="height">The height.</param> /// <returns></returns> public static Image ScaleImage( Image image, int width, int height) { // http://stackoverflow.com/questions/249587/high-quality-image-scaling-c-sharp // http://stackoverflow.com/questions/6821261/after-resizing-white-image-gets-gray-border // NO "using" here, because the image is returned (and // would be disposed by "using")! var result = new Bitmap(image, width, height); result.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (var g = Graphics.FromImage(result)) { g.CompositingQuality = CompositingQuality.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; var ia = new ImageAttributes(); ia.SetWrapMode(WrapMode.TileFlipXY); g.DrawImage( image, new Rectangle( 0, 0, width, height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, ia); return result; } }
void Resize(string extension, Bitmap original, double ratio, Stream output) { int newWidth = (int)(original.Width * ratio); int newHeight = (int)(original.Height * ratio); Bitmap resized = new Bitmap(newWidth, newHeight, original.PixelFormat); resized.SetResolution(original.HorizontalResolution, original.VerticalResolution); Graphics g; switch (extension.ToLower()) { case ".jpg": case ".jpeg": g = Graphics.FromImage(resized); break; default: Bitmap temp = new Bitmap(resized.Width, resized.Height); g = Graphics.FromImage(temp); g.DrawImage(resized, new Rectangle(0, 0, temp.Width, temp.Height), 0, 0, resized.Width, resized.Height, GraphicsUnit.Pixel); resized = temp; break; } using (g) { g.PageUnit = GraphicsUnit.Pixel; g.InterpolationMode = InterpolationMode.HighQualityBicubic; g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; g.CompositingMode = CompositingMode.SourceCopy; g.CompositingQuality = CompositingQuality.HighQuality; using (ImageAttributes attr = new ImageAttributes()) { attr.SetWrapMode(WrapMode.TileFlipXY); g.DrawImage(original, new Rectangle(0, 0, newWidth, newHeight), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attr); } resized.Save(output, ImageFormat.Jpeg); } }
/// <summary> /// Generates a full set of mipmaps for the texture. /// </summary> /// <param name="overwriteExistingMipmaps">true if the existing mipmap set is replaced with the new set; false otherwise.</param> public virtual void GenerateMipmaps(bool overwriteExistingMipmaps) { var imageAttr = new ImageAttributes(); imageAttr.SetWrapMode(WrapMode.TileFlipXY); // If we already have mipmaps and we're not supposed to overwrite // them then return without any generation. if (!overwriteExistingMipmaps && faces.Any(f => f.Count > 1)) return; // Generate the mips for each face. foreach (var face in faces) { // Remove any existing mipmaps. var faceBitmap = face[0]; face.Clear(); face.Add(faceBitmap); int width = faceBitmap.Width, height = faceBitmap.Height; while (width > 1 && height > 1) { var systemBitmap = face[face.Count-1].ToSystemBitmap(); width /= 2; height /= 2; var bitmap = new Bitmap(width,height); using (var graphics = System.Drawing.Graphics.FromImage(bitmap)) { var destRect = new System.Drawing.Rectangle(0, 0, width, height); graphics.InterpolationMode = InterpolationMode.HighQualityBilinear; graphics.DrawImage(systemBitmap, destRect, 0, 0, width * 2, height * 2, GraphicsUnit.Pixel, imageAttr); } face.Add(bitmap.ToXnaBitmap(false)); //we dont want to flip textures twice systemBitmap.Dispose(); } } }
/// <summary> /// Verilen Ölçülerde Bitmap'i boyutlandırır. /// </summary> /// <param name="Height">Yükselik Değeri</param> /// <param name="Width">Genişlik Değeri</param> /// <param name="OrjBitmap">Orijinal Bitmap</param> public Bitmap ImageResize(Bitmap OrjBitmap, int Width, int Height) { try { Bitmap thumb = new Bitmap(Width, Height); Graphics mGraphs = Graphics.FromImage(thumb); if (OrjBitmap.RawFormat != ImageFormat.Png) { mGraphs.InterpolationMode = InterpolationMode.High; mGraphs.CompositingQuality = CompositingQuality.HighQuality; mGraphs.SmoothingMode = SmoothingMode.AntiAlias; mGraphs.PixelOffsetMode = PixelOffsetMode.HighQuality; } else { mGraphs.SmoothingMode = SmoothingMode.None; mGraphs.InterpolationMode = InterpolationMode.NearestNeighbor; mGraphs.SmoothingMode = SmoothingMode.None; mGraphs.PixelOffsetMode = PixelOffsetMode.None; } System.Drawing.Imaging.ImageAttributes attr = new System.Drawing.Imaging.ImageAttributes(); attr.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY); mGraphs.DrawImage(OrjBitmap, 0, 0, thumb.Width, thumb.Height); mGraphs.Dispose(); attr.Dispose(); //thumb.Dispose(); return(thumb); } catch (Exception) { return(null); } }
// partially based on http://stackoverflow.com/questions/10964179/colormatrix-for-partial-gray-scale public Bitmap MinifyAndGrayscale(Image image) { var destRect = new Rectangle(0, 0, WIDTH, HEIGHT); var minified = new Bitmap(WIDTH, HEIGHT, PixelFormat.Format32bppRgb); using (var g = Graphics.FromImage(minified)) { g.CompositingMode = CompositingMode.SourceCopy; g.CompositingQuality = CompositingQuality.HighQuality; g.InterpolationMode = InterpolationMode.HighQualityBilinear; g.SmoothingMode = SmoothingMode.HighQuality; g.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var attributes = new ImageAttributes()) { attributes.SetWrapMode(WrapMode.TileFlipXY); attributes.SetColorMatrix(matrix); g.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes); return minified; } } }
public static Image ResizeImage(this Image sourceImage, int width, int height) { var destinationRectangle = new Rectangle(0, 0, width, height); var destinationImage = new Bitmap(width, height); destinationImage.SetResolution(sourceImage.HorizontalResolution, sourceImage.VerticalResolution); using (var graphicsSurface = Graphics.FromImage(destinationImage)) { // Various settings to ensure quality is not lost in the resizing. graphicsSurface.CompositingMode = CompositingMode.SourceCopy; graphicsSurface.CompositingQuality = CompositingQuality.HighQuality; graphicsSurface.InterpolationMode = InterpolationMode.HighQualityBicubic; graphicsSurface.SmoothingMode = SmoothingMode.HighQuality; graphicsSurface.PixelOffsetMode = PixelOffsetMode.HighQuality; using (var wrapMode = new ImageAttributes()) { wrapMode.SetWrapMode(WrapMode.TileFlipXY); graphicsSurface.DrawImage(sourceImage, destinationRectangle, 0, 0, sourceImage.Width, sourceImage.Height, GraphicsUnit.Pixel, wrapMode); } } return destinationImage; }
public static Bitmap ResizeImage(Image image, int width, int height) { var destRect = new Rectangle(0, 0, width, height); var destImage = new Bitmap(width, height); destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution); using (var graphics = System.Drawing.Graphics.FromImage(destImage)) { graphics.CompositingMode = CompositingMode.SourceCopy; graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.Default; graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Default; graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.Default; graphics.PixelOffsetMode = PixelOffsetMode.Default; using (var wrapMode = new System.Drawing.Imaging.ImageAttributes()) { wrapMode.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY); graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, System.Drawing.GraphicsUnit.Pixel, wrapMode); } } return(destImage); }
/// <summary> /// Creates a jpg-thumbnail for a given file. Needed for preview images in the website. /// </summary> /// <param name="filename">Filename of the local base file.</param> /// <param name="baseUrl">URL of the source location to create subfolders.</param> public static void GenerateThumbs(string filename, string baseUrl, int maxWidth, int maxHeight) { var OutputFile = Constants.DataOutput + Constants.DataThumbsResult + "_" + maxWidth + "px\\"; var folder = ""; // Split thumbnails based on source to get a nicer structure and to reduce files per folder. if (baseUrl.Contains("wiki")) folder = "wiki\\"; else if (baseUrl.Contains("gfycat")) folder = "gfycat\\"; OutputFile += folder + Path.GetFileNameWithoutExtension(filename) + ".jpg"; // Replace common html special characters to get cleaner file names. OutputFile = OutputFile.Replace("%20", " "); OutputFile = OutputFile.Replace("%27", "'"); OutputFile = OutputFile.Replace("%28", "("); OutputFile = OutputFile.Replace("%29", ")"); if (File.Exists(OutputFile)) return; var dirName = Path.GetDirectoryName(OutputFile); if (dirName != null) Directory.CreateDirectory(dirName); var row = Console.CursorTop; Console.Write("Generating a thumb for " + filename); Image image; try { image = Image.FromFile(filename); } catch (OutOfMemoryException) { ErrorHandler.ShowWarning("File " + filename + " might be corrupted. Remove it and run this again."); return; } ScaleImageSize(ref maxWidth, ref maxHeight, image.Width, image.Height); var destRect = new Rectangle(0, 0, maxWidth, maxHeight); var destImage = new Bitmap(maxWidth, maxHeight); 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); } } // Some copypaste encoder stuff for a 90% quality. ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg); System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 90L); myEncoderParameters.Param[0] = myEncoderParameter; destImage.Save(OutputFile, jpgEncoder, myEncoderParameters); Helper.ClearConsoleLine(row); }
public void GenerateField(bool update_filters = false) { dominoes = new int[length, height]; System.Drawing.Image i; if (!update_filters) { using (var bmpTemp = new System.Drawing.Bitmap(SourcePath)) { i = new System.Drawing.Bitmap(bmpTemp); } } else { i = ImageHelper.BitmapImageToBitmap(filters.preview); } if (length < 2) { m_length = 2; } if (height < 2) { m_height = 2; } System.Drawing.Bitmap thumb = new System.Drawing.Bitmap(length, height); System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(thumb); graphics.Clear(System.Drawing.Color.White); if (ResizeMode == 0) { graphics.InterpolationMode = InterpolationMode.NearestNeighbor; } if (ResizeMode == 1) { graphics.InterpolationMode = InterpolationMode.Bicubic; } if (ResizeMode == 2) { graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; } System.Drawing.Imaging.ImageAttributes attr = new System.Drawing.Imaging.ImageAttributes(); System.Drawing.Imaging.ImageAttributes Att = new System.Drawing.Imaging.ImageAttributes(); Att.SetWrapMode(System.Drawing.Drawing2D.WrapMode.TileFlipXY); graphics.DrawImage(i, new System.Drawing.Rectangle(0, 0, length, height), 0, 0, i.Width, i.Height, System.Drawing.GraphicsUnit.Pixel, Att); //graphics.DrawImage(i, 0, 0, length, height); BitmapImage bitmapImage = ImageHelper.BitmapToBitmapImage(thumb); BitmapSource bitm = new FormatConvertedBitmap(bitmapImage, PixelFormats.Bgr24, null, 0); WriteableBitmap b = BitmapFactory.ConvertToPbgra32Format(bitm); IColorSpaceComparison comp; switch (ColorRegressionMode) { case 0: comp = new CmcComparison(); break; case 1: comp = new Cie1976Comparison(); break; case 2: comp = new Cie94Comparison(); break; default: comp = new CieDe2000Comparison(); break; } Dithering d; switch (DiffusionMode) { case 0: d = new NoDithering(comp, Colors); break; case 1: d = new FloydSteinbergDithering(comp, Colors); break; case 2: d = new JarvisJudiceNinkeDithering(comp, Colors); break; default: d = new StuckiDithering(comp, Colors); break; } dominoes = d.Dither(b, comp); b.Lock(); }
/// <summary> /// 创建缩略图 /// </summary> public static string CutAvatar(string imgSrc, int x, int y, int width, int height, long Quality, ResFileType rft, int t) { try { imgSrc = RWUtility.GetResPath(imgSrc); string dirPath = string.Empty; if (ResConfig.Current.Icons.ContainsKey(rft)) { IconInfo size = ResConfig.Current.Icons[rft]; dirPath = Path.GetDirectoryName(imgSrc) + string.Format("\\{0}x{1}\\", size.Width, size.Height); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } Image original = Image.FromFile(imgSrc); Bitmap img = new Bitmap(t, t, PixelFormat.Format24bppRgb); img.MakeTransparent(img.GetPixel(0, 0)); img.SetResolution(72, 72); using (Graphics gr = Graphics.FromImage(img)) { if (original.RawFormat.Equals(ImageFormat.Jpeg) || original.RawFormat.Equals(ImageFormat.Png) || original.RawFormat.Equals(ImageFormat.Bmp)) { gr.Clear(Color.Transparent); } if (original.RawFormat.Equals(ImageFormat.Gif)) { gr.Clear(Color.White); } gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.SmoothingMode = SmoothingMode.AntiAlias; gr.CompositingQuality = CompositingQuality.HighQuality; gr.PixelOffsetMode = PixelOffsetMode.HighQuality; gr.TextRenderingHint = System.Drawing.Text.TextRenderingHint.ClearTypeGridFit; using (var attribute = new System.Drawing.Imaging.ImageAttributes()) { attribute.SetWrapMode(WrapMode.TileFlipXY); gr.DrawImage(original, new Rectangle(0, 0, t, t), x, y, width, height, GraphicsUnit.Pixel, attribute); } } ImageCodecInfo myImageCodecInfo = GetEncoderInfo("image/jpeg"); if (original.RawFormat.Equals(ImageFormat.Jpeg)) { myImageCodecInfo = GetEncoderInfo("image/jpeg"); } else if (original.RawFormat.Equals(ImageFormat.Png)) { myImageCodecInfo = GetEncoderInfo("image/png"); } else if (original.RawFormat.Equals(ImageFormat.Gif)) { myImageCodecInfo = GetEncoderInfo("image/gif"); } else if (original.RawFormat.Equals(ImageFormat.Bmp)) { myImageCodecInfo = GetEncoderInfo("image/bmp"); } System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality; EncoderParameters myEncoderParameters = new EncoderParameters(1); EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, Quality); myEncoderParameters.Param[0] = myEncoderParameter; img.Save(dirPath + Path.GetFileName(imgSrc), myImageCodecInfo, myEncoderParameters); } return(dirPath + Path.GetFileName(imgSrc)); } catch { return(""); } }