I tried this:
string str = System.IO.Path.GetFileName(txtImage.Text);
string pth = System.IO.Directory.GetCurrentDirectory() + "\\Subject";
string fullpath = pth + "\\" + str;
Image NewImage = clsImage.ResizeImage(fullpath, 130, 140, true);
NewImage.Save(fullpath, ImageFormat.Jpeg);
public static Image ResizeImage(string file, int width, int height, bool onlyResizeIfWider)
{
if (File.Exists(file) == false)
return null;
try
{
using (Image image = Image.FromFile(file))
{
// Prevent using images internal thumbnail
image.RotateFlip(RotateFlipType.Rotate180FlipNone);
image.RotateFlip(RotateFlipType.Rotate180FlipNone);
if (onlyResizeIfWider == true)
{
if (image.Width <= width)
{
width = image.Width;
}
}
int newHeight = image.Height * width / image.Width;
if (newHeight > height)
{
// Resize with height instead
width = image.Width * height / image.Height;
newHeight = height;
}
Image NewImage = image.GetThumbnailImage(width, newHeight, null, IntPtr.Zero);
return NewImage;
}
}
catch (Exception )
{
return null;
}
}
Running the above code, I get an image 4-5 KB in size with very poor image quality.
The original image file is no more than 1.5 MB large. How can I improve the image quality of the results?
I think you should use Image Resizer, its free and resizing an image is very easy using it.
var settings = new ResizeSettings {
MaxWidth = thumbnailSize,
MaxHeight = thumbnailSize,
Format = "jpg"
};
settings.Add("quality", quality.ToString());
ImageBuilder.Current.Build(inStream, outStream, settings);
resized = outStream.ToArray();
You can also install it using Nuget package manager.
PM> Install-Package ImageResizer
Related
I'm trying to minify image from url, my code is this
public static string GetBreaker(string fileName)
{
string cacheBreaker = null;
try
{
if (fileName.StartsWith("~"))
{
fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName.Remove(0));
}
cacheBreaker = File.GetLastWriteTime(fileName).ToFileTime().ToString();
}
catch { }
return string.IsNullOrEmpty(cacheBreaker) ? string.Empty : string.Format("?cachebreaker={0}", cacheBreaker);
}
public static void SaveJpeg(string path, System.Drawing.Image img, int quality)
{
if (quality < 0 || quality > 100)
throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");
EncoderParameter qualityParam =
new EncoderParameter(Encoder.Quality, quality);
ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
EncoderParameters encoderParams = new EncoderParameters(1);
encoderParams.Param[0] = qualityParam;
img.Save(path, jpegCodec, encoderParams);
}
private static ImageCodecInfo GetEncoderInfo(string mimeType)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
for (int i = 0; i < codecs.Length; i++)
if (codecs[i].MimeType == mimeType)
return codecs[i];
return null;
}
protected void Button1_Click(object sender, EventArgs e)
{
System.Drawing.Image myImage = System.Drawing.Image.FromFile(ImageUrltxt.Text.ToString());
SaveJpeg(#"~/mintemp/demo.jpg", myImage, 50);
}
I'm getting error like this:
URI formats are not supported.
in
System.Drawing.Image myImage = System.Drawing.Image.FromFile(ImageUrltxt.Text.ToString());
Can anyone help me to solve out this problem. I'm very new to programming. Thanks in advance, sorry for my bad English.
1. First you have to check out your uri path is correct or not eg:
string uriPath = "file:\\C:\\Users\\john\\documents\\visual studio 2010\\Projects\\proj";
or
string localPath = new Uri(uriPath).LocalPath;
2. You have to add the uri of the image as correct Please check your uri path of image is correct.
SaveJpeg(#"~/mintemp/demo.jpg", myImage, 50);
3. This is coded in c# (for reference) resizing and compressing of image in c#
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
private Boolean CheckFileType(String fileName)
{
String ext = Path.GetExtension(fileName) ;
switch (ext.ToLower())
{
case ".gif":
return true;
case ".png":
return true;
case ".jpg":
return true;
case ".jpeg":
return true;
case ".bmp":
return true;
default:
return false;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
const int bmpW = 300;// //New image target width
const int bmpH = 226;// //New Image target height
if (FileUpload1.HasFile)
{
//Clear the error label text
lblError.Text = "";
//Check to make sure the file to upload has a picture file format extention
//and set the target width and height
if (this.CheckFileType(FileUpload1.FileName))
{
Int32 newWidth = bmpW;
Int32 newHeight = bmpH;
//Use the uploaded filename for saving without the "." extension
String upName = FileUpload1.FileName.Substring(0, FileUpload1.FileName.IndexOf("."));
//Mid(FileUpload1.FileName, 1, (InStr(FileUpload1.FileName, ".") - 1)) ;
//Set the save path of the resized image, you will need this directory already created in your web site
String filePath = "~/Upload/" + upName + ".jpg";
//Create a new Bitmap using the uploaded picture as a Stream
//Set the new bitmap resolution to 72 pixels per inch
Bitmap upBmp = (Bitmap)Bitmap.FromStream(FileUpload1.PostedFile.InputStream);
Bitmap newBmp = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
newBmp.SetResolution(72, 72);
//Get the uploaded image width and height
Int32 upWidth = upBmp.Width;
Int32 upHeight = upBmp.Height;
Int32 newX = 0; //Set the new top left drawing position on the image canvas
Int32 newY = 0;
Decimal reDuce;
//Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions
//to ensure the image is always in the centre of the canvas vertically and horizontally
if (upWidth > upHeight)
{
//Landscape picture
reDuce = newWidth / upWidth;
//calculate the width percentage reduction as decimal
newHeight = ((Int32)(upHeight * reDuce));
//reduce the uploaded image height by the reduce amount
newY = ((Int32)((bmpH - newHeight) / 2));
//Position the image centrally down the canvas
newX = 0; //Picture will be full width
}
else
{
if (upWidth < upHeight)
{
//Portrait picture
reDuce = newHeight / upHeight;
//calculate the height percentage reduction as decimal
newWidth = ((Int32)(upWidth * reDuce));
//reduce the uploaded image height by the reduce amount
newX = ((Int32)((bmpW - newWidth) / 2));
//Position the image centrally across the canvas
newY = 0; //Picture will be full hieght
}
else
{
if (upWidth == upHeight)
{
//square picture
reDuce = newHeight / upHeight;
//calculate the height percentage reduction as decimal
newWidth = ((Int32)((upWidth * reDuce)));
//reduce the uploaded image height by the reduce amount
newX = ((Int32)(((bmpW - newWidth) / 2))); //Position the image centrally across the canvas
newY = ((Int32)(((bmpH - newHeight) / 2))); //Position the image centrally down the canvas
}
}
}
//Create a new image from the uploaded picture using the Graphics class
//Clear the graphic and set the background colour to white
//Use Antialias and High Quality Bicubic to maintain a good quality picture
//Save the new bitmap image using //Png// picture format and the calculated canvas positioning
Graphics newGraphic = Graphics.FromImage(newBmp);
try
{
newGraphic.Clear(Color.White);
newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newGraphic.DrawImage(upBmp, newX, newY, newWidth, newHeight);
newBmp.Save(MapPath(filePath), System.Drawing.Imaging.ImageFormat.Jpeg);
//Show the uploaded resized picture in the image control
Image1.ImageUrl = filePath;
Image1.Visible = true;
}
catch (Exception ex)
{
lblError.Text = ex.ToString();
throw ex;
}
finally
{
upBmp.Dispose();
newBmp.Dispose();
newGraphic.Dispose();
}
}
else
{
lblError.Text = "Please select a picture with a file format extension of either Bmp, Jpg, Jpeg, Gif or Png.";
}
}
}
}
I want to insert two different sizes of images using single file upload.
I had inserted one image which has size 101 but I need to insert another 51 size small image of the same user, for that I need my own method.
id BigImage SmallImage
1 mazhar.jpg NULL
2 12_n.jpg NULL
I need result like below:
id BigImage SmallImage
1 mazhar.jpg smallmazhar.jpg
2 12_n.jpg small12_n.jpg
C# code is given below:
protected void Button1_Click(object sender, EventArgs e)
{
//http://forums.asp.net/t/1079883.aspx?PageIndex=1
string Status = string.Empty;
int id = 0;
const int bmpW = 101;
//New image target width
const int bmpH = 101;
//New Image target height
bo.Para1 = FileUpload1.FileName.ToString();// Passing parameter
if ((FileUpload1.HasFile))
{
//Clear the error label text
lblError.Text = "";
//Check to make sure the file to upload has a picture file format extention and set the target width and height
if ((CheckFileType(FileUpload1.FileName)))
{
Int32 newWidth = bmpW;
Int32 newHeight = bmpH;
//Use the uploaded filename for saving without the '.' extension
String upName = FileUpload1.FileName.Substring(0, FileUpload1.FileName.IndexOf("."));
//Set the save path of the resized image, you will need this directory already created in your web site
// string filePath = "~/Upload/" + upName + ".jpg";
bl.Insert_PhotoInfo(bo, out Status, out id);
string filePath = Convert.ToString(id) + bo.Para1;
FileUpload1.PostedFile.SaveAs(Request.ServerVariables["APPL_PHYSICAL_PATH"] + "Upload/" + filePath);
//Create a new Bitmap using the uploaded picture as a Stream
//Set the new bitmap resolution to 72 pixels per inch
Bitmap upBmp = (Bitmap)Bitmap.FromStream(FileUpload1.PostedFile.InputStream);
Bitmap newBmp = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
newBmp.SetResolution(72, 72);
//Get the uploaded image width and height
Double upWidth = upBmp.Width;
Double upHeight = upBmp.Height;
int newX = 0;
//Set the new top left drawing position on the image canvas
int newY = 0;
Double reDuce;
//Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions
//to ensure the image is always in the centre of the canvas vertically and horizontally
if (upWidth > upHeight)
{
//Landscape picture
reDuce = newWidth / upWidth;
//calculate the width percentage reduction as decimal
newHeight = ((Int32)(upHeight * reDuce));
//reduce the uploaded image height by the reduce amount
newY = ((Int32)((bmpH - newHeight) / 2));
//Position the image centrally down the canvas
newX = 0;
//Picture will be full width
}
else if (upWidth < upHeight)
{
//Portrait picture
reDuce = newHeight / upHeight;
//calculate the height percentage reduction as decimal
newWidth = ((Int32)(upWidth * reDuce));
//reduce the uploaded image height by the reduce amount
newX = ((Int32)((bmpW - newWidth) / 2));
//Position the image centrally across the canvas
newY = 0;
//Picture will be full hieght
}
else if (upWidth == upHeight)
{
//square picture
reDuce = newHeight / upHeight;
//calculate the height percentage reduction as decimal
newWidth = ((Int32)(upWidth * reDuce));
//reduce the uploaded image height by the reduce amount
newX = ((Int32)((bmpW - newWidth) / 2));
//Position the image centrally across the canvas
newY = ((Int32)((bmpH - newHeight) / 2));
//Position the image centrally down the canvas
}
//Create a new image from the uploaded picture using the Graphics class
//Clear the graphic and set the background colour to white
//Use Antialias and High Quality Bicubic to maintain a good quality picture
//Save the new bitmap image using 'Png' picture format and the calculated canvas positioning
Graphics newGraphic = Graphics.FromImage(newBmp);
try
{
newGraphic.Clear(Color.White);
newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newGraphic.DrawImage(upBmp, newX, newY, newWidth, newHeight);
newBmp.Save(MapPath(filePath), System.Drawing.Imaging.ImageFormat.Jpeg);
//Show the uploaded resized picture in the image control
Image1.ImageUrl = filePath;
Image1.Visible = true;
}
catch (Exception ex)
{
string newError = ex.Message;
lblError.Text = newError;
}
finally
{
upBmp.Dispose();
newBmp.Dispose();
newGraphic.Dispose();
}
}
else
{
lblError.Text = "Please select a picture with a file format extension of either Bmp, Jpg, Jpeg, Gif or Png.";
}
}
}
Here is your updated code:
protected void Button1_Click(object sender, EventArgs e){
UploadImage(101, "Big");
UploadImage(51, "Small");
}
protected void UploadImage(int size, string name){
//http://forums.asp.net/t/1079883.aspx?PageIndex=1
string Status = string.Empty;
int id = 0;
const int bmpW = size;
//New image target width
const int bmpH = size;
//New Image target height
bo.Para1 = FileUpload1.FileName.ToString() + name;// Passing parameter
if ((FileUpload1.HasFile))
{
//Clear the error label text
lblError.Text = "";
//Check to make sure the file to upload has a picture file format extention and set the target width and height
if ((CheckFileType(FileUpload1.FileName)))
{
Int32 newWidth = bmpW;
Int32 newHeight = bmpH;
//Use the uploaded filename for saving without the '.' extension
String upName = FileUpload1.FileName.Substring(0, FileUpload1.FileName.IndexOf("."));
//Set the save path of the resized image, you will need this directory already created in your web site
// string filePath = "~/Upload/" + upName + ".jpg";
bl.Insert_PhotoInfo(bo, out Status, out id);
string filePath = Convert.ToString(id) + bo.Para1;
FileUpload1.PostedFile.SaveAs(Request.ServerVariables["APPL_PHYSICAL_PATH"] + "Upload/" + filePath);
//Create a new Bitmap using the uploaded picture as a Stream
//Set the new bitmap resolution to 72 pixels per inch
Bitmap upBmp = (Bitmap)Bitmap.FromStream(FileUpload1.PostedFile.InputStream);
Bitmap newBmp = new Bitmap(newWidth, newHeight, System.Drawing.Imaging.PixelFormat.Format24bppRgb);
newBmp.SetResolution(72, 72);
//Get the uploaded image width and height
Double upWidth = upBmp.Width;
Double upHeight = upBmp.Height;
int newX = 0;
//Set the new top left drawing position on the image canvas
int newY = 0;
Double reDuce;
//Keep the aspect ratio of image the same if not 4:3 and work out the newX and newY positions
//to ensure the image is always in the centre of the canvas vertically and horizontally
if (upWidth > upHeight)
{
//Landscape picture
reDuce = newWidth / upWidth;
//calculate the width percentage reduction as decimal
newHeight = ((Int32)(upHeight * reDuce));
//reduce the uploaded image height by the reduce amount
newY = ((Int32)((bmpH - newHeight) / 2));
//Position the image centrally down the canvas
newX = 0;
//Picture will be full width
}
else if (upWidth < upHeight)
{
//Portrait picture
reDuce = newHeight / upHeight;
//calculate the height percentage reduction as decimal
newWidth = ((Int32)(upWidth * reDuce));
//reduce the uploaded image height by the reduce amount
newX = ((Int32)((bmpW - newWidth) / 2));
//Position the image centrally across the canvas
newY = 0;
//Picture will be full hieght
}
else if (upWidth == upHeight)
{
//square picture
reDuce = newHeight / upHeight;
//calculate the height percentage reduction as decimal
newWidth = ((Int32)(upWidth * reDuce));
//reduce the uploaded image height by the reduce amount
newX = ((Int32)((bmpW - newWidth) / 2));
//Position the image centrally across the canvas
newY = ((Int32)((bmpH - newHeight) / 2));
//Position the image centrally down the canvas
}
//Create a new image from the uploaded picture using the Graphics class
//Clear the graphic and set the background colour to white
//Use Antialias and High Quality Bicubic to maintain a good quality picture
//Save the new bitmap image using 'Png' picture format and the calculated canvas positioning
Graphics newGraphic = Graphics.FromImage(newBmp);
try
{
newGraphic.Clear(Color.White);
newGraphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
newGraphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
newGraphic.DrawImage(upBmp, newX, newY, newWidth, newHeight);
newBmp.Save(MapPath(filePath), System.Drawing.Imaging.ImageFormat.Jpeg);
//Show the uploaded resized picture in the image control
Image1.ImageUrl = filePath;
Image1.Visible = true;
}
catch (Exception ex)
{
string newError = ex.Message;
lblError.Text = newError;
}
finally
{
upBmp.Dispose();
newBmp.Dispose();
newGraphic.Dispose();
}
}
else
{
lblError.Text = "Please select a picture with a file format extension of either Bmp, Jpg, Jpeg, Gif or Png.";
}
}
}
I let users upload a banner with a minimum width of 400px. This image will then get a wide of 1110px.
I try to upload images with the following sizes: 960x390, 410x410, 784x250.
When i upload 784x250, the image get the same size 784x250 not the width, 1110px.
I use this:
int Height;
using (var Bmp = new Bitmap(str))
{
if (Bmp.Width < 400)
{
throw;
}
if (Bmp.Height < 150)
{
throw;
}
Height = Bmp.Height;
}
if (Height > 300)
{
Height = 300;
}
str.Position = 0;
var ImageData = str.StreamToByteArray();
var Settings = "width=1110;height="+ Height + ";format=jpg;mode=crop;"
var Setting = new ResizeSettings(Settings);
using (var Out = new MemoryStream())
{
using (var In = new MemoryStream(ImageData))
{
In.Seek(0, SeekOrigin.Begin);
var I = new ImageJob(In, Out, Setting)
{
CreateParentDirectory = false
};
I.Build();
}
Out.Position = 0;
// Upload to blob
}
(str contains a stream with the image)
I want the image to be 1110px wide and max 300px high.
Whats wrong?
ImageResizer does not upscale images unless you specifically ask for it via scale=both or scale=canvas. Upscaling is typically undesired.
Also, you can pass the stream directly to ImageJob and simplify your code significantly.
str.Seek(0, SeekOrigin.Begin);
var Out = new MemoryStream(8096);
new ImageJob(str, Out, new Instructions("width=1110;height="+ Height + ";format=jpg;mode=crop;scale=both")).Build();
Out.Seek(0, SeekOrigin.Begin);
The other sizes you tested each have a Bmp.Height > 300 which means the image requires to be cropped.
However when using an image size 784x250, the image doesn't require to be cropped. So you'll never re-size the image.
Assuming you wish to keep the image proportionally correct, you should first re-size the image to match the wanted width and afterwards crop the exceeding height if necessary.
var image = new Bitmap(str);
var ratio = (double)1110 / image.Width;
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);
var bmp = new Bitmap(newImage);
if(bmp.Height > 300){
//Resize again using crop, like you did in your original code.
}
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);
I want that suppose user upload 2 MB image then from that image i want to generate 1 thumbnail image.
To reduce its size , so i can get speed in loading.
as my listing page contains many images.so i am getting to much loading time.
SO can you tell me how can i compress image or get Thumbnail image???
You can do something like this:
public static Bitmap CreateThumbnail(string filename, int width, int height)
{
Bitmap bmpOut = null;
try
{
Bitmap loBMP = new Bitmap(filename);
ImageFormat loFormat = loBMP.RawFormat;
decimal lnRatio;
int lnNewWidth = 0;
int lnNewHeight = 0;
//*** If the image is smaller than a thumbnail just return it
if (loBMP.Width < width && loBMP.Height < height)
return loBMP;
if (loBMP.Width > loBMP.Height)
{
lnRatio = (decimal)width / loBMP.Width;
lnNewWidth = width;
decimal lnTemp = loBMP.Height * lnRatio;
lnNewHeight = (int)lnTemp;
}
else
{
lnRatio = (decimal)height / loBMP.Height;
lnNewHeight = height;
decimal lnTemp = loBMP.Width * lnRatio;
lnNewWidth = (int)lnTemp;
}
bmpOut = new Bitmap(lnNewWidth, lnNewHeight);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, lnNewWidth, lnNewHeight);
g.DrawImage(loBMP, 0, 0, lnNewWidth, lnNewHeight);
loBMP.Dispose();
}
catch
{
return null;
}
return bmpOut;
}
Is only a prototype but you can use it for your project