Hello i'm using this function in order to resize/upload an image . There's any quick adjustment i could make in order to improve the resized image quality without changing the full function?
FileUpload FileUpload1 =(FileUpload)ListView1.InsertItem.FindControl("FileUpload1");
string virtualFolder = "~/albume/";
string physicalFolder = Server.MapPath(virtualFolder);
string fileName = Guid.NewGuid().ToString();
string extension = System.IO.Path.GetExtension(FileUpload1.FileName);
FileUpload1.SaveAs(System.IO.Path.Combine(physicalFolder, fileName + extension));
//test resize
System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath("~/albume/") + fileName + extension);
int srcWidth = img.Width;
int srcHeight = img.Height;
int thumbHeight = (int)((800.0 / srcWidth) * srcHeight);
System.Drawing.Image thumb = img.GetThumbnailImage(800, thumbHeight, null, IntPtr.Zero);
img.Dispose();
FileUpload1.Dispose();
thumb.Save(Server.MapPath("~/albume/") + fileName + extension, System.Drawing.Imaging.ImageFormat.Jpeg);
//end resize
myAlbum.poza = fileName + extension;
instead of this code:
thumb.Save(Server.MapPath("~/albume/") + fileName + extension, System.Drawing.Imaging.ImageFormat.Jpeg);
use this one :
System.Drawing.Imaging.ImageCodecInfo[] info = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders();
System.Drawing.Imaging.EncoderParameters param = new System.Drawing.Imaging.EncoderParameters(1);
param.Param[0] = new System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 100L);
thumb.Save(Server.MapPath("~/albume/") + fileName + extension, info[1], param);
use this snippet:
Bitmap newImage = new Bitmap(newWidth, newHeight);
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
}
stolen from this question/answer: Resizing an Image without losing any quality see Kris's ultra voted answer and vote it up :)
On my site, I use the following code to resize user images before they are sent to the page.
You may be able to make use of something similar - try investigating the various Interpolation modes.
using (Graphics graphics = Graphics.FromImage(target))
{
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighSpeed;
graphics.CompositingMode = System.Drawing.Drawing2D.CompositingMode.SourceCopy;
graphics.Clear(ColorTranslator.FromHtml("#F4F6F5"));
graphics.DrawImage(bmp, 0, 0, 145, 145);
using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
{
target.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg);
memoryStream.WriteTo(context.Response.OutputStream);
}
}
The best is not to use "GetThumbnailImage" this makes low quality. According to http://msdn.microsoft.com/de-de/library/system.drawing.image.getthumbnailimage%28VS.80%29.aspx
Resize the image by redrawing it like:
private static Image resizeImage(Image imgToResize, Size size)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
nPercentW = ((float)size.Width / (float)sourceWidth);
nPercentH = ((float)size.Height / (float)sourceHeight);
if (nPercentH < nPercentW)
nPercent = nPercentH;
else
nPercent = nPercentW;
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
found on
Related
What I am trying to do here is:
Download an image
Save it to disk
Resize etc
Save it with a new name
Delete the old image
I have achieved everything but not the last step. I get the "file in use" error.
This is the code:
filenameb = "img-1b.jpg";//old img
fullpathb = Path.Combine(dir, filenameb);//old img path
//downloading using imglink
client.DownloadFile(imglink, fullpathb);//save old img as %dir%\img-1b.jpg
//until here I downloaded the "old" img
filename = "img-1.jpg";//new img
fullpath = Path.Combine(dir, filename);//new img path
//name and fullpath for the "new img" are set
Image imgresize = Image.FromFile(fullpathb);//give old img path
imgresize = FixedSize(imgresize);//resize
imgresize.Save(fullpath, ImageFormat.Jpeg);//save new img as %dir%\img-1.jpg
//EVERYTHING WORKS PERFECTLY UP TO HERE
imgresize.Dispose();//dispose -has old img path
System.IO.File.Delete(fullpathb);//delete old img
I also dispose the image in FixedSize.
And this is the code of "FixedSize" if needed:
//kind of messed up to save some space
static Image FixedSize(Image imgPhoto)
{
int Width = 300;int Height = 250;
int sourceWidth = imgPhoto.Width;int sourceHeight = imgPhoto.Height;
int sourceX = 0;int sourceY = 0;int destX = 0;int destY = 0;
float nPercent = 0;float nPercentW = 0;float nPercentH = 0;
nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);
if (nPercentH < nPercentW){ nPercent = nPercentH;
destX = (int)((Width - (sourceWidth * nPercent)) / 2);}
else { nPercent = nPercentW;
destY = (int)((Height - (sourceHeight * nPercent)) / 2); }
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap bmPhoto = new Bitmap(Width, Height, PixelFormat.Format24bppRgb);
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
grPhoto.Clear(Color.White);
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
I am really new to this and I can't realise what i'm doing wrong (or what i am not doing at all). Any help is appreciated!
Image imgresize = Image.FromFile(fullpathb)
This is going to lock the file. Instead, create an image from a MemoryStream of bytes read from the file
byte[] imageBytes = FileReadAllBytes(fullpathb);
using (var ms = new MemoryStream(imageBytes)){
var image = Image.FromStream(ms);
}
Untested
I'm taking a screenshot of my form and then sending it to the printer. The image is too large, it goes off the sides of the page. I've been looking around for the past few hours to no avail. Can someone assist?
When I open the file itself it looks good in a print preview. If I then print from the preview its fine. But I wanted to do this with no user intervention.
public void SetupPrintHandler()
{
PrintDocument printDoc = new PrintDocument();
printDoc.PrintPage += new PrintPageEventHandler(OnPrintPage);
printDoc.DefaultPageSettings.Landscape = true;
printDoc.Print();
}
private void OnPrintPage(object sender, PrintPageEventArgs args)
{
using (Image image = Image.FromFile(#"C:/temp2.bmp"))
{
Graphics g = args.Graphics;
g.DrawImage(image, 0, 0);
}
}
private void printscreen()
{
ScreenCapture sc = new ScreenCapture();
Image img = sc.CaptureScreen();
sc.CaptureWindowToFile(this.Handle, "C:/temp2.bmp", ImageFormat.Bmp);
SetupPrintHandler();
}
So what I did just now as instead of the screen shot, for testing, I save what was in panel3 which is 2 pictureboxes. So i'm taking the size of panel3.
Bitmap bmp = new Bitmap(panel3.ClientSize.Width, panel3.ClientSize.Height);
panel3.DrawToBitmap(bmp, panel3.ClientRectangle);
bmp.Save(subPath + file + ".bmp");
Which again, looks great on a print preview and if I click print from the print preview it prints fine. But if I just send it straight to the printer it doesn't fit. So maybe its not a size issue but a setting I have to send to the printer when not using print preview?
Update
So I may have found the issue. When you un-check "Fit to frame" when printing a picture it fits perfectly. However there doesn't seem to be an option when sending directly to the printer the way I am where I can disable "Fit to frame"
If you want to resize and keep the aspect of the image I do the following
public Stream ResizeImage(Stream stream, ImageFormat imageFormat, int width, int height)
{
var originalImage = Image.FromStream(stream);
var sourceWidth = originalImage.Width;
var sourceHeight = originalImage.Height;
const int sourceX = 0;
const int sourceY = 0;
var destX = 0;
var destY = 0;
float nPercent;
var nPercentW = ((float)width / sourceWidth);
var nPercentH = ((float)height / sourceHeight);
if (nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = Convert.ToInt16((width - (sourceWidth * nPercent)) / 2);
}
else
{
nPercent = nPercentW;
destY = Convert.ToInt16((height - (sourceHeight * nPercent)) / 2);
}
var destWidth = (int)(sourceWidth * nPercent);
var destHeight = (int)(sourceHeight * nPercent);
// specify different formats based off type ( GIF and PNG need alpha channel - 32aRGB 8bit Red 8bit Green 8bit B 8bit Alpha)
Bitmap newImage;
if (imageFormat.Equals(ImageFormat.Png) || imageFormat.Equals(ImageFormat.Gif))
{
newImage = new Bitmap(width, height, PixelFormat.Format32bppArgb);
}
else
{
newImage = new Bitmap(width, height, PixelFormat.Format24bppRgb);
}
newImage.SetResolution(originalImage.HorizontalResolution, originalImage.VerticalResolution);
var newGraphics = Graphics.FromImage(newImage);
// don't clear the buffer with white if we have transparency
if (!imageFormat.Equals(ImageFormat.Png) && !imageFormat.Equals(ImageFormat.Gif))
{
newGraphics.Clear(Color.White);
}
newGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
newGraphics.DrawImage(originalImage,
new Rectangle(destX, destY, destWidth, destHeight),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
newGraphics.Dispose();
originalImage.Dispose();
var memoryStream = new MemoryStream();
newImage.Save(memoryStream, imageFormat);
memoryStream.Position = 0;
return memoryStream;
}
Using this you can resize the image. You need to pick up a scaling size before print.
As example - rescale 'image' to 227x171 pixels.
image = new Bitmap(image, new Size(227, 171));
I have to display image in photo gallery # width=200 height=180, but while uploading images I have to resize it , but the problem is every image have different resolution. How can I resize the images with different resolution so that images remain intact.
Here is my code :
private void ResizeImage()
{
System.Drawing.Image ImageToUpload = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
byte[] image = null;
int h = ImageToUpload.Height;
int w = ImageToUpload.Width;
int r = int.Parse(ImageToUpload.VerticalResolution.ToString());
int NewWidth = 200;//constant
int NewHeight = 180;//constant
byte[] imagesize = FileUpload1.FileBytes;
System.Drawing.Bitmap BitMapImage = new System.Drawing.Bitmap(ImageToUpload, NewWidth, NewHeight);//this line gives horrible output
MemoryStream Memory = new MemoryStream();
BitMapImage.Save(Memory, System.Drawing.Imaging.ImageFormat.Jpeg);
Memory.Position = 0;
image = new byte[Memory.Length + 1];
Memory.Read(image, 0, image.Length);
}
if resolution is 96 and if I set maxwidth=200 then its height would be 150 then only the image looks small and accurate. Can't we resize image in desired way so that it looks exact?
The function will resize the image maintaining aspect ratio.
public static Image Resize(Image originalImage, int w, int h)
{
//Original Image attributes
int originalWidth = originalImage.Width;
int originalHeight = originalImage.Height;
// Figure out the ratio
double ratioX = (double)w / (double)originalWidth;
double ratioY = (double)h / (double)originalHeight;
// use whichever multiplier is smaller
double ratio = ratioX < ratioY ? ratioX : ratioY;
// now we can get the new height and width
int newHeight = Convert.ToInt32(originalHeight * ratio);
int newWidth = Convert.ToInt32(originalWidth * ratio);
Image thumbnail = new Bitmap(newWidth, newHeight);
Graphics graphic = Graphics.FromImage(thumbnail);
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
graphic.Clear(Color.Transparent);
graphic.DrawImage(originalImage, 0, 0, newWidth, newHeight);
return thumbnail;
}
Usage
Image BitMapImage = Resize(ImageToUpload, NewWidth, NewHeight);
Here i keep height fixed to 180 to maintain aspect ratio. It will resize the image and save to disk. The return value is the percentage value which i use in 'background-size' css.
public float ResizePhoto(string filepath, string filename)
{
var path = Path.Combine(filepath, filename);
var newPath = Path.Combine(filepath, "sml_" + filename);
Image orgImage = Image.FromFile(path);
float fixedHt = 180f;
int destHeight, destWidth;
float reqScale;
if(orgImage.Height > fixedHt)
{
destHeight = (int)fixedHt;
destWidth = (int)(fixedHt / orgImage.Height * orgImage.Width);
reqScale = destWidth / destHeight * 100;
}
else
{
destHeight = orgImage.Height;
destWidth = orgImage.Width;
reqScale = fixedHt / destHeight * 100;
}
Bitmap bmp = new Bitmap(destWidth, destHeight);
bmp.SetResolution(orgImage.HorizontalResolution,orgImage.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmp);
grPhoto.DrawImage(orgImage,
new Rectangle(0, 0, destWidth, destHeight),
new Rectangle(0, 0, orgImage.Width, orgImage.Height),
GraphicsUnit.Pixel);
bmp.Save(newPath);
return reqScale;
}
How would you resize a JPEG image, to a fixed width whilst keeping aspect ratio? In a simple way, whilst preserving quality.
This will scale in the vertical axis only:
public static Image ResizeImageFixedWidth(Image imgToResize, int width)
{
int sourceWidth = imgToResize.Width;
int sourceHeight = imgToResize.Height;
float nPercent = ((float)width / (float)sourceWidth);
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
Bitmap b = new Bitmap(destWidth, destHeight);
Graphics g = Graphics.FromImage((Image)b);
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imgToResize, 0, 0, destWidth, destHeight);
g.Dispose();
return (Image)b;
}
If you are reducing the width by 25 percent to a fixed value, you must reduce the height by 25 percent.
If you are increasing the width by 25 percent to a fixed value, you must increasing the height by 25 percent.
It's really straight forward.
Assuming there is a (double width) variable:
Image imgOriginal = Bitmap.FromFile(path);
double height = (imgOriginal.Height * width) / imgOriginal.Width;
Image imgnew = new Bitmap((int)width, (int)height, PixelFormat.Format32bppArgb);
Graphics g = Graphics.FromImage(imgnew);
g.DrawImage(imgOriginal, new Point[]{new Point(0,0), new Point(width, 0), new Point(0, height)}, new Rectangle(0,0,imgOriginal.Width, imgOriginal.Height), GraphicsUnit.Pixel);
In the end you´ll have a new image with widthxheight, then, you´ll need to flush the graphics e save the imgnew.
I think there are plenty of samples of this if you search for them. Here's the one I commonly use...
public static Stream ResizeGdi(Stream stream, System.Drawing.Size size)
{
Image image = Image.FromStream(stream);
int width = image.Width;
int height = image.Height;
int sourceX = 0, sourceY = 0, destX = 0, destY = 0;
float percent = 0, percentWidth = 0, percentHeight = 0;
percentWidth = ((float)size.Width / (float)width);
percentHeight = ((float)size.Height / (float)height);
int destW = 0;
int destH = 0;
if (percentHeight < percentWidth)
{
percent = percentHeight;
}
else
{
percent = percentWidth;
}
destW = (int)(width * percent);
destH = (int)(height * percent);
MemoryStream mStream = new MemoryStream();
if (destW == 0
&& destH == 0)
{
image.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
return mStream;
}
using (Bitmap bitmap = new Bitmap(destW, destH, System.Drawing.Imaging.PixelFormat.Format48bppRgb))
{
using (System.Drawing.Graphics graphics = System.Drawing.Graphics.FromImage(bitmap))
{
//graphics.Clear(Color.Red);
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.DrawImage(image,
new Rectangle(destX, destY, destW, destH),
new Rectangle(sourceX, sourceY, width, height),
GraphicsUnit.Pixel);
}
bitmap.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
}
mStream.Position = 0;
return mStream as Stream;
}
Example of the calling code...
Stream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.None);
resizedStream = ImageUtility.ResizeGdi(stream, new System.Drawing.Size(resizeWidth, resizeHeight));
A quick search on code project has found the following article. It allows for resizing of images which accepts a boolean to restrain the new image to keep the originals aspect ratio. I'm unsure of what the quality is like as no screenshots were provided. See the article here
I'm using Digital Persona Finger Print device and need to capture the image as WSQ format instead of Bmp format
Using C# DigitalPersona One Touch for Windows SDK
Sample Code
private DPFP.Capture.SampleConversion SampleConversion;
private Bitmap Image;
public async void OnComplete(object Capture, string ReaderSerialNumber, DPFP.Sample Sample)
{
var imgName = string.Format("fingerprint{0}.bmp", DateTime.Now.Ticks);
SampleConversion.ConvertToPicture(Sample, ref Image);
Image.Save(imgName, System.Drawing.Imaging.ImageFormat.Bmp);
}
I found library in C# that convert bmp to wsq wsqEncodeDecode but the result of wsq are not correct, Any solution that return the captured image in wsq format directly from the sdk?
To Achieve exactly what i need i do the following:
I used 2 libraries
1 - AForge.Imaging , AForge.Imaging.Formats and Delta.Wsq DLL's
private Bitmap Image;
public async void OnComplete(object Capture, string ReaderSerialNumber, DPFP.Sample Sample)
{
SampleConversion.ConvertToPicture(Sample, ref Image);
Image.RotateFlip(RotateFlipType.Rotate180FlipNone);
Image = resizeImage(364, 400, Image);
var img8bppx = Grayscale.CommonAlgorithms.BT709.Apply(Image);
var rawImageData = Conversions.GdiImageToImageInfo(img8bppx);
WsqEncoder encoder = new WsqEncoder();
var result = encoder.Encode(rawImageData);
}
And is method to do resize
public Bitmap resizeImage(int newWidth, int newHeight, Image imgPhoto)
{
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;
}