Image resize without saving on disk - c#

in asp.net i want to resize the image and display on some control but without saving on disk.
is there any free utility just like for clasic asp.
http://www.aspjpeg.com/livedemo.html

This Thumbnail class will do the job.
public class Thumbnail
{
private string _filePath;
private int _maxWidth = 120;
private int _maxHeight = 120;
public string MimeType;
public System.Drawing.Imaging.ImageFormat ImageFormat;
public byte[] ImageBytes;
public Thumbnail(string filePath, int maxWidth, int maxHeight)
{
_filePath = filePath;
_maxWidth = maxWidth;
_maxHeight = maxHeight;
MakeThumbnail();
}
private void MakeThumbnail()
{
using (Image img = new Bitmap(_filePath))
{
Size newSize = GenerateImageDimensions(img.Width, img.Height, _maxWidth, _maxHeight);
int imgWidth = newSize.Width;
int imgHeight = newSize.Height;
// create the thumbnail image
using (Image img2 =
img.GetThumbnailImage(imgWidth, imgHeight,
new Image.GetThumbnailImageAbort(Abort),
IntPtr.Zero))
{
using (Graphics g = Graphics.FromImage(img2)) // Create Graphics object from original Image
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
//BMP 0, JPEG 1 , GIF 2 , TIFF 3, PNG 4
System.Drawing.Imaging.ImageCodecInfo codec;
switch (Path.GetExtension(_filePath))
{
case ".gif":
codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[2];
ImageFormat = System.Drawing.Imaging.ImageFormat.Gif;
MimeType = "image/gif";
break;
case ".png":
codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[4];
ImageFormat = System.Drawing.Imaging.ImageFormat.Png;
MimeType = "image/png";
break;
default: //jpg
codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;
MimeType = "image/jpg";
break;
}
//Set the parameters for defining the quality of the thumbnail... here it is set to 100%
System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);
//Now draw the image on the instance of thumbnail Bitmap object
g.DrawImage(img, new Rectangle(0, 0, img2.Width, img2.Height));
MemoryStream ms = new MemoryStream();
img2.Save(ms, codec, eParams);
ImageBytes = new byte[ms.Length];
ImageBytes = ms.ToArray();
ms.Close();
ms.Dispose();
}
}
}
}
public static Size GenerateImageDimensions(int currW, int currH, int destW, int destH)
{
int imgWidth = currW;
int imgHeight = currH;
if (imgWidth > destW)
{
double rate = (double)imgWidth / (double)destW;
imgWidth = destW;
imgHeight = (int)(imgHeight / rate);
}
if (imgHeight > destH)
{
double rate = (double)imgHeight / (double)destH;
imgHeight = destH;
imgWidth = (int)(imgWidth / rate);
}
return new Size(imgWidth, imgHeight);
}
private bool Abort()
{
return false;
}
}
Using is simple, just put this on your page codebehind. Browser output will be resized image.
Thumbnail thm = new Thumbnail("c:\some_image.jpg", 300, 300);
Response.ContentType = thm.MimeType;
Response.BinaryWrite(thm.ImageBytes);

This is probably what you need:
http://imageresizing.net/

Related

How to compress images before storing them in asp.net?

This is my add image code.
protected void SubmitButton_Click(object sender, EventArgs e)
{
ProductImages productImage = new ProductImages();
productImage.ProductID = Convert.ToInt32(ProductDropDownList.SelectedValue.ToString());
if (!FileUpload1.HasFile)
{
MessageLabel1.Text = "Please Select Image File"; //checking if file uploader has no file selected
}
else
{
int length = FileUpload1.PostedFile.ContentLength;
productImage.ProductImage = new byte[length];
FileUpload1.PostedFile.InputStream.Read(productImage.ProductImage, 0, length);
try
{
ProductImageBL.AddProductImages(productImage);
MessageLabel1.Text = "Product Image has been successfully added!";
}
catch (Exception ex)
{
MessageLabel1.Text = "Some error occured while processing the request. Error Description <br/>" + ex.Message;
}
}
}
Image compression depends on image type and what is on image. Photos of real life objects are typically in .jpg and you can't compress them much without noticeable quality losing.
Probably what you really want to do - is resize image to smaller size like 500*500 if you know this will be enought for all your needs. Keep in mind to save image aspect ratio during resizing.
Related SO question:
Resize an Image C#
The SO link posted by dlxeon is excellent. I use the examples there myself.
However all those examples resize the image, but you can also increase the compression in jpeg files and\or decrease the DPI.
Below a complete example of how to resize and compress a jpeg. It also checks if the image needs rotating in case the phone was held vertical for example. And you can add padding if you want to make the image square.
Note that if you use this example as is the transparency of .png and .gif files will be lost because they are converted to jpg.
protected void SubmitButton_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == true)
{
using (Bitmap postedImage = new Bitmap(FileUpload1.PostedFile.InputStream))
{
byte [] bin = Common.scaleImage(postedImage, 400, 400, false);
Image1.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(bin);
}
}
}
public static byte[] scaleImage(Image image, int maxWidth, int maxHeight, bool padImage)
{
try
{
int newWidth;
int newHeight;
byte[] returnArray;
//check if the image needs rotating (eg phone held vertical when taking a picture for example)
foreach (var prop in image.PropertyItems)
{
if (prop.Id == 0x0112)
{
int rotateValue = image.GetPropertyItem(prop.Id).Value[0];
RotateFlipType flipType = getRotateFlipType(rotateValue);
image.RotateFlip(flipType);
break;
}
}
//apply padding if needed
if (padImage == true)
{
image = applyPaddingToImage(image);
}
//check if the with or height of the image exceeds the maximum specified, if so calculate the new dimensions
if (image.Width > maxWidth || image.Height > maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
newWidth = (int)(image.Width * ratio);
newHeight = (int)(image.Height * ratio);
}
else
{
newWidth = image.Width;
newHeight = image.Height;
}
//start with a new image
var newImage = new Bitmap(newWidth, newHeight);
//set the new resolution, 72 is usually good enough for displaying images on monitors
newImage.SetResolution(72, 72);
//or use the original resolution
//newImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);
//resize the image
using (var graphics = Graphics.FromImage(newImage))
{
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
}
image = newImage;
//save the image to a memorystream to apply the compression level, higher compression = better quality = bigger images
using (MemoryStream ms = new MemoryStream())
{
EncoderParameters encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, 80L);
image.Save(ms, getEncoderInfo("image/jpeg"), encoderParameters);
//save the stream as byte array
returnArray = ms.ToArray();
}
//cleanup
image.Dispose();
newImage.Dispose();
return returnArray;
}
catch (Exception ex)
{
//there was an error: ex.Message
return null;
}
}
private static ImageCodecInfo getEncoderInfo(string mimeType)
{
ImageCodecInfo[] encoders = ImageCodecInfo.GetImageEncoders();
for (int j = 0; j < encoders.Length; ++j)
{
if (encoders[j].MimeType.ToLower() == mimeType.ToLower())
return encoders[j];
}
return null;
}
private static Image applyPaddingToImage(Image image)
{
//get the maximum size of the image dimensions
int maxSize = Math.Max(image.Height, image.Width);
Size squareSize = new Size(maxSize, maxSize);
//create a new square image
Bitmap squareImage = new Bitmap(squareSize.Width, squareSize.Height);
using (Graphics graphics = Graphics.FromImage(squareImage))
{
//fill the new square with a color
graphics.FillRectangle(Brushes.Red, 0, 0, squareSize.Width, squareSize.Height);
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.HighQuality;
graphics.SmoothingMode = SmoothingMode.HighQuality;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
//put the original image on top of the new square
graphics.DrawImage(image, (squareSize.Width / 2) - (image.Width / 2), (squareSize.Height / 2) - (image.Height / 2), image.Width, image.Height);
}
return squareImage;
}
private static RotateFlipType getRotateFlipType(int rotateValue)
{
RotateFlipType flipType = RotateFlipType.RotateNoneFlipNone;
switch (rotateValue)
{
case 1:
flipType = RotateFlipType.RotateNoneFlipNone;
break;
case 2:
flipType = RotateFlipType.RotateNoneFlipX;
break;
case 3:
flipType = RotateFlipType.Rotate180FlipNone;
break;
case 4:
flipType = RotateFlipType.Rotate180FlipX;
break;
case 5:
flipType = RotateFlipType.Rotate90FlipX;
break;
case 6:
flipType = RotateFlipType.Rotate90FlipNone;
break;
case 7:
flipType = RotateFlipType.Rotate270FlipX;
break;
case 8:
flipType = RotateFlipType.Rotate270FlipNone;
break;
default:
flipType = RotateFlipType.RotateNoneFlipNone;
break;
}
return flipType;
}

Image upload quality bad

I have an application that uploads images to a database and then show them in a webpage by using a Handler. My problem is that the images are showing in a different quality and color than the original ones. I don't know what the problem is.
File = FileUpload1.PostedFile;
imgbin = new Byte[File.ContentLength];
File.InputStream.Read(imgbin, 0, File.ContentLength);
imagename = FileUpload1.FileName;
// Here the image size is defined --------------------
System.Drawing.Image UploadedImage = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
UploadedImageWidth = UploadedImage.PhysicalDimension.Width;
UploadedImageHeight = UploadedImage.PhysicalDimension.Height;
//Resize Image
int compressWidth;
if (UploadedImageWidth >639)
{
compressWidth = 640;
}
else
{
compressWidth = Convert.ToInt32(UploadedImageWidth);
}
ResizeImage compressPicture = new ResizeImage();
imgbin = compressPicture.ResizeImageFile(imgbin, compressWidth);
System.Drawing.Image Image = System.Drawing.Image.FromStream(new MemoryStream(imgbin));
public class ResizeImage
{
public byte[] ResizeImageFile(byte[] imageFile, int targetSize) // Set targetSize to 1024
{
using (System.Drawing.Image oldImage = System.Drawing.Image.FromStream(new MemoryStream(imageFile)))
{
Size newSize = CalculateDimensions(oldImage.Size, targetSize);
using (Bitmap newImage = new Bitmap(newSize.Width, newSize.Height, PixelFormat.Format64bppPArgb))
{
byte[] byteArray = new byte[0];
using (Graphics canvas = Graphics.FromImage(newImage))
{
canvas.Clear(Color.White);
canvas.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
canvas.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
canvas.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
canvas.DrawImage(oldImage, new Rectangle(new Point(0, 0), newSize));
int quality = 100;
ImageCodecInfo codec = RetrieveCodec("image/jpeg");
using (MemoryStream m = new MemoryStream())
{
using (EncoderParameters codeParams = new EncoderParameters())
{
using (EncoderParameter p = new EncoderParameter(Encoder.Quality, quality))
{
codeParams.Param[0] = p;
newImage.Save(m, codec, codeParams);
byteArray = m.ToArray();
}
}
}
return byteArray;
}
}
}
}
private ImageCodecInfo RetrieveCodec(string mimeType)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.MimeType == mimeType)
return codec;
}
return null;
}
public static Size CalculateDimensions(Size oldSize, int targetSize)
{
decimal ajusteTamaño;
Size newSize = new Size();
if (oldSize.Width > targetSize)
{
ajusteTamaño = oldSize.Width / Convert.ToDecimal(targetSize);
newSize.Width = (int)(oldSize.Width / ajusteTamaño);
newSize.Height = (int)(oldSize.Height / ajusteTamaño);
}
else
{
newSize.Width = oldSize.Width;
newSize.Height = oldSize.Height;
}
return newSize;
}
}

Convert varbinary(max) to image,resize and save it in a folder using c# or vb.net?

public static BinaryToImage(System.Data.Linq.Binary binaryData)
{
if (binaryData == null) {
return null;
}
byte[] buffer = binaryData.ToArray();
System.Drawing.Image newImage = default(System.Drawing.Image);
MemoryStream memStream = new MemoryStream();
memStream.Write(buffer, 0, buffer.Length);
using (MemoryStream strefgham = new MemoryStream(buffer)) {
newImage = System.Drawing.Image.FromStream(strefgham);
return newImage;
}
}
public static double GetPercent(double width,double height,int originalWidth,int originalHeight)
{
if (width <= originalWidth && height <= originalHeight) {
return 1.0;
} else
{
double wid = (originalWidth / width);
double hei = (originalHeight / height);
return (wid < hei) ? wid : hei;
}
}
System.Drawing.Image newImage = default(System.Drawing.Image);
newImage = BinaryToImage(VarBinaryName.ToArray());
double perc = GetPercent(newImage.Width, newImage.Height, 300, 300);
double newWidth = newImage.Width * perc;
double newHeight = newImage.Height * perc;
int disWeight = Convert.ToInt32(newWidth);
int disHeight = Convert.ToInt32(newHeight);
So far i am able to convert the varbinary(max) to image, and resized it.But not able to save it in a folder. Is this something to do with Bitmap? Any suggestions?
Hey add this line to save your image in folder
if (!Directory.Exists("D:\Test"))
{
Directory.CreateDirectory("D:\Test");
}
newImage.Save(#"D:\Test\New.jpg", origImage.RawFormat);

Resize byte[] of Image

After reading from file dialog I want to resize a picture. I have the done the following code. Now I want to resize the stream of picture. How do I do it?
Stream stream = (Stream)openFileDialog.File.OpenRead();
byte[] bytes = new byte[stream.Length];
There is no need to declare a byte[], to resize an image just use
Image image = Image.FromFile(fileName);
check this other answer to see how to scale the image aftewards
try this
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
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.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
Usage
Image img = Image.FromStream(stream);
Image thumb = ScaleImage(img);
stream.Close();
stream.Dispose();
stream = new MemoryStream();
thumb.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
I have an picturebox. I load an image, resizing and conveting to byte at last sending to sqllite. Maybe it can be hlepfıull to you Code is below.
private static byte[] byteResim = null;
private void btnResimEkle_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Resimdosyası seçiniz.";
openFileDialog1.Filter = "Resim files (*.jpg)|*.jpg|Tüm dosyalar(*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string resimYol = openFileDialog1.FileName; // File name of the image
picResim.Image = Image.FromFile(resimYol);// picResim is name of picturebox
picResim.Image = YenidenBoyutlandir(new Bitmap(picResim.Image)); //this method resizing the image
Image UyeResim = picResim.Image; // and this four block converting to image to byte
MemoryStream ms = new MemoryStream();
UyeResim.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byteResim = ms.ToArray(); // byteResim variable format Byte[]
}
}
Image YenidenBoyutlandir(Image resim)// resizing image method
{
Image yeniResim = new Bitmap(150, 156);
using (Graphics abc = Graphics.FromImage((Bitmap)yeniResim))
{
abc.DrawImage(resim, new System.Drawing.Rectangle(0, 0, 150, 156));
}
return yeniResim;
}

Why does resizing a png image lose transparency?

I am trying to resize an image as follows. I return the resized image into byte[] so that I can store it in database. The transparency of png image is lost. Please help to make this better.
private byte[] GetThumbNail(string imageFile, Stream imageStream,
int imageLen)
{
try
{
Image.GetThumbnailImageAbort imageCallBack =
new Image.GetThumbnailImageAbort(ThumbnailCallback);
Bitmap getBitmap = new Bitmap(imageFile);
byte[] returnByte = new byte[imageLen];
Image getThumbnail = getBitmap.GetThumbnailImage(160, 59,
imageCallBack, IntPtr.Zero);
using (Graphics g = Graphics.FromImage(getThumbnail))
{
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode =
System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(getThumbnail, 0, 0, 160, 59);
}
using (MemoryStream ms = new MemoryStream())
{
getThumbnail.Save(ms, ImageFormat.Png);
getThumbnail.Save("test.png", ImageFormat.Png);
returnByte = ms.ToArray();
}
return returnByte;
}
catch (Exception)
{
throw;
}
}
Your code doesn't do quite what you think that it does...
You use the GetThumbnailImage to resize the image, then you draw the thumbnail image into itself which is rather pointless. You probably lose the transparency in the first step.
Create a blank bitmap instead, and resize the source image by drawing it on the blank bitmap.
private byte[] GetThumbNail(string imageFile) {
try {
byte[] result;
using (Image thumbnail = new Bitmap(160, 59)) {
using (Bitmap source = new Bitmap(imageFile)) {
using (Graphics g = Graphics.FromImage(thumbnail)) {
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.DrawImage(source, 0, 0, 160, 59);
}
}
using (MemoryStream ms = new MemoryStream()) {
thumbnail.Save(ms, ImageFormat.Png);
thumbnail.Save("test.png", ImageFormat.Png);
result = ms.ToArray();
}
}
return result;
} catch (Exception) {
throw;
}
}
(I removed some parameters that were never used for anything that had anything to do with the result, like the imageLen parameter that was only used to create a byte array that was never used.)
Try using the .MakeTransparent() call on your bitmap object.
May be you should do something like this because this thing worked for me:
String path = context.Server.MapPath("/images");
if (!path.EndsWith("\\"))
path += "\\";
path += "none.png";
Image img = CreateThumbnail(Image.FromFile(path));
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Png);
ms.WriteTo(context.Response.OutputStream);
private System.Drawing.Image CreateThumbnail(System.Drawing.Image i)
{
int dWidth = i.Width;
int dHeight = i.Height;
int dMaxSize = 150;
if (dWidth > dMaxSize)
{
dHeight = (dHeight * dMaxSize) / dWidth;
dWidth = dMaxSize;
}
if (dHeight > dMaxSize)
{
dWidth = (dWidth * dMaxSize) / dHeight;
dHeight = dMaxSize;
}
return i.GetThumbnailImage(dWidth, dHeight, delegate() { return false; }, IntPtr.Zero);
}

Categories