Usando C# ¿cómo puedo cambiar el tamaño de una imagen jpeg? Una muestra de código sería genial.Usando C# ¿cómo puedo cambiar el tamaño de una imagen jpeg?
Respuesta
C# (o más bien: el .NET framework) en sí mismo no ofrece esa capacidad, pero sí ofrece Bitmap de System.Drawing para acceder fácilmente a los datos en bruto de píxeles de varios formatos de imagen. Para el resto, vea http://en.wikipedia.org/wiki/Image_scaling
Buen filtro de tamaño libre y código de ejemplo.
http://code.google.com/p/zrlabs-yael/
private void MakeResizedImage(string fromFile, string toFile, int maxWidth, int maxHeight)
{
int width;
int height;
using (System.Drawing.Image image = System.Drawing.Image.FromFile(fromFile))
{
DetermineResizeRatio(maxWidth, maxHeight, image.Width, image.Height, out width, out height);
using (System.Drawing.Image thumbnailImage = image.GetThumbnailImage(width, height, new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback), IntPtr.Zero))
{
if (image.Width < thumbnailImage.Width && image.Height < thumbnailImage.Height)
File.Copy(fromFile, toFile);
else
{
ImageCodecInfo ec = GetCodecInfo();
EncoderParameters parms = new EncoderParameters(1);
parms.Param[0] = new EncoderParameter(Encoder.Compression, 40);
ZRLabs.Yael.BasicFilters.ResizeFilter rf = new ZRLabs.Yael.BasicFilters.ResizeFilter();
//rf.KeepAspectRatio = true;
rf.Height = height;
rf.Width = width;
System.Drawing.Image img = rf.ExecuteFilter(System.Drawing.Image.FromFile(fromFile));
img.Save(toFile, ec, parms);
}
}
}
}
Observe que este fragmento de código no es suficiente, debe agregar una referencia al proyecto (el último cambio fue el 6 de noviembre de 2006) – itsho
Ejemplo agradable.
public static Image ResizeImage(Image sourceImage, int maxWidth, int maxHeight)
{
// Determine which ratio is greater, the width or height, and use
// this to calculate the new width and height. Effectually constrains
// the proportions of the resized image to the proportions of the original.
double xRatio = (double)sourceImage.Width/maxWidth;
double yRatio = (double)sourceImage.Height/maxHeight;
double ratioToResizeImage = Math.Max(xRatio, yRatio);
int newWidth = (int)Math.Floor(sourceImage.Width/ratioToResizeImage);
int newHeight = (int)Math.Floor(sourceImage.Height/ratioToResizeImage);
// Create new image canvas -- use maxWidth and maxHeight in this function call if you wish
// to set the exact dimensions of the output image.
Bitmap newImage = new Bitmap(newWidth, newHeight, PixelFormat.Format32bppArgb);
// Render the new image, using a graphic object
using (Graphics newGraphic = Graphics.FromImage(newImage))
{
using (var wrapMode = new ImageAttributes())
{
wrapMode.SetWrapMode(WrapMode.TileFlipXY);
newGraphic.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
}
// Set the background color to be transparent (can change this to any color)
newGraphic.Clear(Color.Transparent);
// Set the method of scaling to use -- HighQualityBicubic is said to have the best quality
newGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Apply the transformation onto the new graphic
Rectangle sourceDimensions = new Rectangle(0, 0, sourceImage.Width, sourceImage.Height);
Rectangle destinationDimensions = new Rectangle(0, 0, newWidth, newHeight);
newGraphic.DrawImage(sourceImage, destinationDimensions, sourceDimensions, GraphicsUnit.Pixel);
}
// Image has been modified by all the references to it's related graphic above. Return changes.
return newImage;
}
Especificar un 'WrapMode' como en la respuesta de LucidObscurity g te da un mejor resultado. Es posible que desee agregar eso a su código. – Andrew
public static class ImageHelper
{
/// <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;
}
public static Bitmap ResizeImage(Image image, decimal percentage)
{
int width = (int)Math.Round(image.Width * percentage, MidpointRounding.AwayFromZero);
int height = (int)Math.Round(image.Height * percentage, MidpointRounding.AwayFromZero);
return ResizeImage(image, width, height);
}
}
class Program
{
static void Main(string[] args)
{
string fileName = @"C:\Images\MyImage.jpg";
FileInfo info = new FileInfo(fileName);
using (Image image = Image.FromFile(fileName))
{
using(Bitmap resizedImage = ImageHelper.ResizeImage(image, 0.25m))
{
resizedImage.Save(
info.DirectoryName + "\\"
+ info.Name.Substring(0, info.Name.LastIndexOf(info.Extension))
+ "_" + resizedImage.Width + "_" + resizedImage.Height
+ info.Extension,
ImageFormat.Jpeg);
}
}
}
}
estoy usando esto:
public static void ResizeJpg(string path, int nWidth, int nHeight)
{
using (var result = new Bitmap(nWidth, nHeight))
{
using (var input = new Bitmap(path))
{
using (Graphics g = Graphics.FromImage((System.Drawing.Image)result))
{
g.DrawImage(input, 0, 0, nWidth, nHeight);
}
}
var ici = ImageCodecInfo.GetImageEncoders().FirstOrDefault(ie => ie.MimeType == "image/jpeg");
var eps = new EncoderParameters(1);
eps.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
result.Save(path, ici, eps);
}
}
- 1. ¿Cómo puedo cambiar el tamaño de una imagen usando Java?
- 2. Cambiar el tamaño de la imagen JPEG al tamaño especificado
- 3. ¿Cómo cambiar el tamaño y dibujar una imagen usando wxpython?
- 4. ¿Cómo puedo cambiar el tamaño de una imagen sin estirarla?
- 5. ¿Cómo cambiar el tamaño de una imagen animada de GIF usando C#?
- 6. Cómo cambiar el tamaño de imagen UIBarButtonItem
- 7. ¿Cómo puedo cambiar el tamaño de una matriz en C?
- 8. Cómo reducir el tamaño de imagen JPEG en Android
- 9. ¿Cómo cambiar el tamaño de una imagen en C# a un cierto tamaño de disco duro?
- 10. Cómo reducir el tamaño del archivo de imagen usando PIL
- 11. Cambio de tamaño de las imágenes (jpeg o imagen descomprimida)
- 12. pyCairo: ¿Cómo cambiar el tamaño y posicionar una imagen?
- 13. ¿Cómo cambiar el tamaño del archivo gif animado usando C#?
- 14. Cambiar el tamaño de una imagen en el balanceo
- 15. Obtener tamaño de imagen de JPEG desde su archivo binario
- 16. UIImageView: ¿Cambiar el tamaño al tamaño de la imagen?
- 17. Obtener tamaño de imagen real, después de cambiar el tamaño
- 18. ¿Cómo cambiar el tamaño de la imagen original en un tamaño de imagen común en Java?
- 19. Obtenga la resolución de una imagen JPEG usando C# y el Entorno .NET?
- 20. ¿Cómo cambiar el tamaño de una imagen a un tamaño de archivo específico?
- 21. Cambiar el tamaño de una imagen en asp.net sin perder la calidad de imagen
- 22. ckfinder cambiar el tamaño de la imagen
- 23. ¿Cómo cambiar el tamaño y flotar a la derecha una imagen de fondo usando css?
- 24. ¿Cómo cambiar el tamaño de una ventana usando JQuery?
- 25. Cambiar una imagen usando jQuery
- 26. Cambiar el tamaño de una imagen con Paperclip
- 27. ¿Cómo puedo cambiar el tamaño de la recaptcha en Greasemonkey?
- 28. Cómo cambiar el color de una imagen usando jquery
- 29. Forma rápida de decodificar una imagen JPEG
- 30. Cambiar el modo de tamaño de una imagen de fondo en el cuadro de imagen
ver este mensaje: https://blogs.msdn.microsoft.com/dotnet/2017/01/19/net-core-image-processing/ – erdinger