visual una tiempo tamaño que imagen hacer ejecucion con como cargar cambie cambiar boton ajustar c# image resize

c# - tiempo - como ajustar una imagen en un boton de visual basic



Cómo cambiar el tamaño de una imagen C# (17)

¿Por qué no usar el método System.Drawing.Image.GetThumbnailImage ?

public Image GetThumbnailImage( int thumbWidth, int thumbHeight, Image.GetThumbnailImageAbort callback, IntPtr callbackData)

Ejemplo:

Image originalImage = System.Drawing.Image.FromStream(inputStream, true, true); Image resizedImage = originalImage.GetThumbnailImage(newWidth, (newWidth * originalImage.Height) / originalWidth, null, IntPtr.Zero); resizedImage.Save(imagePath, ImageFormat.Png);

Fuente: http://msdn.microsoft.com/en-us/library/system.drawing.image.getthumbnailimage.aspx

Como Size , Width y Height son las propiedades Get() de System.Drawing.Image ;
¿Cómo puedo cambiar el tamaño de un objeto de imagen en tiempo de ejecución en C #?

En este momento, estoy creando una nueva Image usando:

// objImage is the original Image Bitmap objBitmap = new Bitmap(objImage, new Size(227, 171));


Cambia el tamaño y guarda una imagen para que se ajuste al ancho y la altura como un lienzo manteniendo la imagen proporcional

using System; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging; using System.IO; namespace Infra.Files { public static class GenerateThumb { /// <summary> /// Resize and save an image to fit under width and height like a canvas keeping things proportional /// </summary> /// <param name="originalImagePath"></param> /// <param name="thumbImagePath"></param> /// <param name="newWidth"></param> /// <param name="newHeight"></param> public static void GenerateThumbImage(string originalImagePath, string thumbImagePath, int newWidth, int newHeight) { Bitmap srcBmp = new Bitmap(originalImagePath); float ratio = 1; float minSize = Math.Min(newHeight, newHeight); if (srcBmp.Width > srcBmp.Height) { ratio = minSize / (float)srcBmp.Width; } else { ratio = minSize / (float)srcBmp.Height; } SizeF newSize = new SizeF(srcBmp.Width * ratio, srcBmp.Height * ratio); Bitmap target = new Bitmap((int)newSize.Width, (int)newSize.Height); using (Graphics graphics = Graphics.FromImage(target)) { graphics.CompositingQuality = CompositingQuality.HighSpeed; graphics.InterpolationMode = InterpolationMode.HighQualityBicubic; graphics.CompositingMode = CompositingMode.SourceCopy; graphics.DrawImage(srcBmp, 0, 0, newSize.Width, newSize.Height); using (MemoryStream memoryStream = new MemoryStream()) { target.Save(thumbImagePath); } } } } }


En esta pregunta , tendrás algunas respuestas, incluida la mía:

public Image resizeImage(int newWidth, int newHeight, string stPhotoPath) { Image imgPhoto = Image.FromFile(stPhotoPath); int sourceWidth = imgPhoto.Width; int sourceHeight = imgPhoto.Height; //Consider vertical pics if (sourceWidth < sourceHeight) { int buff = newWidth; newWidth = newHeight; newHeight = buff; } int sourceX = 0, sourceY = 0, destX = 0, destY = 0; float nPercent = 0, nPercentW = 0, nPercentH = 0; nPercentW = ((float)newWidth / (float)sourceWidth); nPercentH = ((float)newHeight / (float)sourceHeight); if (nPercentH < nPercentW) { nPercent = nPercentH; destX = System.Convert.ToInt16((newWidth - (sourceWidth * nPercent)) / 2); } else { nPercent = nPercentW; destY = System.Convert.ToInt16((newHeight - (sourceHeight * nPercent)) / 2); } int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap bmPhoto = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.Clear(Color.Black); grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); imgPhoto.Dispose(); return bmPhoto; }


En la aplicación que hice fue necesario crear una función con múltiples opciones. Es bastante grande, pero cambia el tamaño de la imagen, puede mantener la relación de aspecto y puede cortar los bordes para devolver solo el centro de la imagen:

/// <summary> /// Resize image with a directory as source /// </summary> /// <param name="OriginalFileLocation">Image location</param> /// <param name="heigth">new height</param> /// <param name="width">new width</param> /// <param name="keepAspectRatio">keep the aspect ratio</param> /// <param name="getCenter">return the center bit of the image</param> /// <returns>image with new dimentions</returns> public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width, Boolean keepAspectRatio, Boolean getCenter) { int newheigth = heigth; System.Drawing.Image FullsizeImage = System.Drawing.Image.FromFile(OriginalFileLocation); // Prevent using images internal thumbnail FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); FullsizeImage.RotateFlip(System.Drawing.RotateFlipType.Rotate180FlipNone); if (keepAspectRatio || getCenter) { int bmpY = 0; double resize = (double)FullsizeImage.Width / (double)width;//get the resize vector if (getCenter) { bmpY = (int)((FullsizeImage.Height - (heigth * resize)) / 2);// gives the Y value of the part that will be cut off, to show only the part in the center Rectangle section = new Rectangle(new Point(0, bmpY), new Size(FullsizeImage.Width, (int)(heigth * resize)));// create the section to cut of the original image //System.Console.WriteLine("the section that will be cut off: " + section.Size.ToString() + " the Y value is minimized by: " + bmpY); Bitmap orImg = new Bitmap((Bitmap)FullsizeImage);//for the correct effect convert image to bitmap. FullsizeImage.Dispose();//clear the original image using (Bitmap tempImg = new Bitmap(section.Width, section.Height)) { Graphics cutImg = Graphics.FromImage(tempImg);// set the file to save the new image to. cutImg.DrawImage(orImg, 0, 0, section, GraphicsUnit.Pixel);// cut the image and save it to tempImg FullsizeImage = tempImg;//save the tempImg as FullsizeImage for resizing later orImg.Dispose(); cutImg.Dispose(); return FullsizeImage.GetThumbnailImage(width, heigth, null, IntPtr.Zero); } } else newheigth = (int)(FullsizeImage.Height / resize);// set the new heigth of the current image }//return the image resized to the given heigth and width return FullsizeImage.GetThumbnailImage(width, newheigth, null, IntPtr.Zero); }

Para facilitar el acceso a la función, es posible agregar algunas funciones sobrecargadas:

/// <summary> /// Resize image with a directory as source /// </summary> /// <param name="OriginalFileLocation">Image location</param> /// <param name="heigth">new height</param> /// <param name="width">new width</param> /// <returns>image with new dimentions</returns> public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width) { return resizeImageFromFile(OriginalFileLocation, heigth, width, false, false); } /// <summary> /// Resize image with a directory as source /// </summary> /// <param name="OriginalFileLocation">Image location</param> /// <param name="heigth">new height</param> /// <param name="width">new width</param> /// <param name="keepAspectRatio">keep the aspect ratio</param> /// <returns>image with new dimentions</returns> public Image resizeImageFromFile(String OriginalFileLocation, int heigth, int width, Boolean keepAspectRatio) { return resizeImageFromFile(OriginalFileLocation, heigth, width, keepAspectRatio, false); }

Ahora son los dos últimos booleanos opcionales para establecer. Llame a la función de esta manera:

System.Drawing.Image ResizedImage = resizeImageFromFile(imageLocation, 800, 400, true, true);


Esta voluntad -

  • Redimensionar ancho Y alto sin la necesidad de un bucle
  • No supera las dimensiones de las imágenes originales.

//////////////

private void ResizeImage(Image img, double maxWidth, double maxHeight) { double resizeWidth = img.Source.Width; double resizeHeight = img.Source.Height; double aspect = resizeWidth / resizeHeight; if (resizeWidth > maxWidth) { resizeWidth = maxWidth; resizeHeight = resizeWidth / aspect; } if (resizeHeight > maxHeight) { aspect = resizeWidth / resizeHeight; resizeHeight = maxHeight; resizeWidth = resizeHeight * aspect; } img.Width = resizeWidth; img.Height = resizeHeight; }


Este código es el mismo que se publicó en una de las respuestas anteriores ... pero convertirá el píxel transparente al blanco en lugar del negro ... Gracias :)

public Image resizeImage(int newWidth, int newHeight, string stPhotoPath) { Image imgPhoto = Image.FromFile(stPhotoPath); int sourceWidth = imgPhoto.Width; int sourceHeight = imgPhoto.Height; //Consider vertical pics if (sourceWidth < sourceHeight) { int buff = newWidth; newWidth = newHeight; newHeight = buff; } int sourceX = 0, sourceY = 0, destX = 0, destY = 0; float nPercent = 0, nPercentW = 0, nPercentH = 0; nPercentW = ((float)newWidth / (float)sourceWidth); nPercentH = ((float)newHeight / (float)sourceHeight); if (nPercentH < nPercentW) { nPercent = nPercentH; destX = System.Convert.ToInt16((newWidth - (sourceWidth * nPercent)) / 2); } else { nPercent = nPercentW; destY = System.Convert.ToInt16((newHeight - (sourceHeight * nPercent)) / 2); } int destWidth = (int)(sourceWidth * nPercent); int destHeight = (int)(sourceHeight * nPercent); Bitmap bmPhoto = new Bitmap(newWidth, newHeight, PixelFormat.Format24bppRgb); bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution); Graphics grPhoto = Graphics.FromImage(bmPhoto); grPhoto.Clear(Color.White); grPhoto.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; grPhoto.DrawImage(imgPhoto, new Rectangle(destX, destY, destWidth, destHeight), new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight), GraphicsUnit.Pixel); grPhoto.Dispose(); imgPhoto.Dispose(); return bmPhoto; }


Este es el código que elaboré para un requisito específico, es decir: el destino siempre está en una relación horizontal. Debería darte un buen comienzo.

public Image ResizeImage(Image source, RectangleF destinationBounds) { RectangleF sourceBounds = new RectangleF(0.0f,0.0f,(float)source.Width, (float)source.Height); RectangleF scaleBounds = new RectangleF(); Image destinationImage = new Bitmap((int)destinationBounds.Width, (int)destinationBounds.Height); Graphics graph = Graphics.FromImage(destinationImage); graph.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; // Fill with background color graph.FillRectangle(new SolidBrush(System.Drawing.Color.White), destinationBounds); float resizeRatio, sourceRatio; float scaleWidth, scaleHeight; sourceRatio = (float)source.Width / (float)source.Height; if (sourceRatio >= 1.0f) { //landscape resizeRatio = destinationBounds.Width / sourceBounds.Width; scaleWidth = destinationBounds.Width; scaleHeight = sourceBounds.Height * resizeRatio; float trimValue = destinationBounds.Height - scaleHeight; graph.DrawImage(source, 0, (trimValue / 2), destinationBounds.Width, scaleHeight); } else { //portrait resizeRatio = destinationBounds.Height/sourceBounds.Height; scaleWidth = sourceBounds.Width * resizeRatio; scaleHeight = destinationBounds.Height; float trimValue = destinationBounds.Width - scaleWidth; graph.DrawImage(source, (trimValue / 2), 0, scaleWidth, destinationBounds.Height); } return destinationImage; }


Esto realizará un cambio de tamaño de alta calidad:

/// <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 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); } } return destImage; }

  • wrapMode.SetWrapMode(WrapMode.TileFlipXY) evita el efecto fantasma alrededor de los bordes de la imagen: el cambio de tamaño ingenuo muestra píxeles transparentes más allá de los límites de la imagen, pero al reflejar la imagen podemos obtener una mejor muestra (esta configuración es muy notable)
  • destImage.SetResolution mantiene el DPI independientemente del tamaño físico; puede aumentar la calidad al reducir las dimensiones de la imagen o al imprimir
  • La composición controla cómo se combinan los píxeles con el fondo: puede que no sea necesario ya que solo estamos dibujando una cosa.
    • graphics.CompositingMode determina si los píxeles de una imagen de origen se sobrescriben o se combinan con píxeles de fondo. SourceCopy especifica que cuando se representa un color, sobrescribe el color de fondo.
    • graphics.CompositingQuality determina el nivel de calidad de representación de las imágenes en capas.
  • graphics.InterpolationMode determina cómo se calculan los valores intermedios entre dos puntos finales
  • graphics.SmoothingMode especifica si las líneas, las curvas y los bordes de las áreas rellenas usan suavizado (también llamado antialiasing); probablemente solo funciona en vectores
  • graphics.PixelOffsetMode afecta la calidad de representación al dibujar la nueva imagen

Mantener la relación de aspecto se deja como un ejercicio para el lector (en realidad, no creo que sea el trabajo de esta función hacer eso por usted).

Además, este es un buen artículo que describe algunos de los escollos con el cambio de tamaño de la imagen. La función anterior cubrirá la mayoría de ellos, pero aún debe preocuparse por saving .


No estoy seguro de qué es tan difícil, haz lo que estabas haciendo, usa el constructor de mapas de bits sobrecargado para crear una imagen redimensionada, lo único que te faltaba era volver al tipo de datos de imagen:

public static Image resizeImage(Image imgToResize, Size size) { return (Image)(new Bitmap(imgToResize, size)); } yourImage = resizeImage(yourImage, new Size(50,50));


Nota: esto no funcionará con ASP.Net Core porque WebImage depende de System.Web, pero en versiones anteriores de ASP.Net usé este fragmento varias veces y fue útil.

String ThumbfullPath = Path.GetFileNameWithoutExtension(file.FileName) + "80x80.jpg"; var ThumbfullPath2 = Path.Combine(ThumbfullPath, fileThumb); using (MemoryStream stream = new MemoryStream(System.IO.File.ReadAllBytes(fullPath))) { var thumbnail = new WebImage(stream).Resize(80, 80); thumbnail.Save(ThumbfullPath2, "jpg"); }



Si estás trabajando con un BitmapSource :

var resizedBitmap = new TransformedBitmap( bitmapSource, new ScaleTransform(scaleX, scaleY));

Si desea un mejor control sobre la calidad, ejecute esto primero:

RenderOptions.SetBitmapScalingMode( bitmapSource, BitmapScalingMode.HighQuality);

(El valor predeterminado es BitmapScalingMode.Linear que es equivalente a BitmapScalingMode.LowQuality ).



Uso este código en mis proyectos y funciona bien.

var ms = new MemoryStream(File.ReadAllBytes(Source)); Bitmap objBitmap = new Bitmap(ms); if (size.Height == 0) { size = objBitmap.Size; } objBitmap = new Bitmap(objBitmap, size); objBitmap.Save(Destination);


Utilice el ejemplo siguiente para cambiar el tamaño de la imagen:

//Example : System.Net.Mime.MediaTypeNames.Image newImage = System.Net.Mime.MediaTypeNames.Image.FromFile("SampImag.jpg"); System.Net.Mime.MediaTypeNames.Image temImag = FormatImage(newImage, 100, 100); //image size modification unction public static System.Net.Mime.MediaTypeNames.Image FormatImage(System.Net.Mime.MediaTypeNames.Image img, int outputWidth, int outputHeight) { Bitmap outputImage = null; Graphics graphics = null; try { outputImage = new Bitmap(outputWidth, outputHeight, System.Drawing.Imaging.PixelFormat.Format16bppRgb555); graphics = Graphics.FromImage(outputImage); graphics.DrawImage(img, new Rectangle(0, 0, outputWidth, outputHeight), new Rectangle(0, 0, img.Width, img.Height), GraphicsUnit.Pixel); return outputImage; } catch (Exception ex) { return img; } }


public static Image resizeImage(Image image, int new_height, int new_width) { Bitmap new_image = new Bitmap(new_width, new_height); Graphics g = Graphics.FromImage((Image)new_image ); g.InterpolationMode = InterpolationMode.High; g.DrawImage(image, 0, 0, new_width, new_height); return new_image; }


public string CreateThumbnail(int maxWidth, int maxHeight, string path) { var image = System.Drawing.Image.FromFile(path); var ratioX = (double)maxWidth / image.Width; var ratioY = (double)maxHeight / image.Height; var ratio = Math.Min(ratioX, ratioY); var newWidth = (int)(image.Width * ratio); var newHeight = (int)(image.Height * ratio); var newImage = new Bitmap(newWidth, newHeight); Graphics thumbGraph = Graphics.FromImage(newImage); thumbGraph.CompositingQuality = CompositingQuality.HighQuality; thumbGraph.SmoothingMode = SmoothingMode.HighQuality; //thumbGraph.InterpolationMode = InterpolationMode.HighQualityBicubic; thumbGraph.DrawImage(image, 0, 0, newWidth, newHeight); image.Dispose(); string fileRelativePath = "newsizeimages/" + maxWidth + Path.GetFileName(path); newImage.Save(Server.MapPath(fileRelativePath), newImage.RawFormat); return fileRelativePath; }

Haga clic aquí http://bhupendrasinghsaini.blogspot.in/2014/07/resize-image-in-c.html