I am trying to put an image on a bigger image. But the inner image was cropped after drawImage(). Here is my code:
Bitmap im = new Bitmap("D:\\Steffen\\New folder\\I1\\I1\\" + filename + ".png");
int sizeX = im.Width;
int sizeY = im.Height;
int size = 0;
bool isWidth = false;
if (sizeX > sizeY)
{
size = sizeX; isWidth = true;
}
else if(sizeY > sizeX)
{
size = sizeY; isWidth = false;
}
filename = filename + "New";
Bitmap bg = new Bitmap(size,size);
SolidBrush brush = new SolidBrush(Color.Aqua);
using (Graphics g = Graphics.FromImage(bg))
{
g.FillRectangle(brush, 0, 0, size, size);
if (isWidth==true)
{
g.DrawImage(im, 0, (size - sizeY) / 2);
}
else if(isWidth==false)
{
g.DrawImage(im, (size-sizeX)/2, 0);
}
}
Thanks in advance
My guess would be the resolution of the image is the issue:
Try it like this:
Bitmap im = new Bitmap("D:\\Steffen\\New folder\\I1\\I1\\" + filename + ".png");
im.SetResolution(96F, 96F);
Related
the sample panorama image url https://upload.wikimedia.org/wikipedia/commons/3/3b/360%C2%B0_Hoher_Freschen_Panorama_2.jpg which i saved in my pc and generate tile from that image programmatically and got
error like out of memory
this line throw the error Bitmap bmLevelSource =
(Bitmap)Bitmap.FromFile(levelSourceImage);
here is my program code in c# which throw the error
double maxZoom = 5;
string FILEPATH = #"C:\test\img.jpg";
string TARGETFOLDER = #"C:\test\Src";
bool REMOVEXISTINGFILES = true;
if (!System.IO.File.Exists(FILEPATH))
{
Console.WriteLine("file not exist");
return;
}
if (maxZoom >= 10)
{
Console.WriteLine("Scale multiplier should be an integer <=10");
return;
}
//Read image
Bitmap bmSource;
try
{
bmSource = (Bitmap)Bitmap.FromFile(FILEPATH);
}
catch
{
Console.WriteLine("image file not valid");
return;
}
//check directory exist
if (!System.IO.Directory.Exists(TARGETFOLDER))
{
System.IO.Directory.CreateDirectory(TARGETFOLDER);
}
else if (REMOVEXISTINGFILES)
{
string[] files = System.IO.Directory.GetFiles(TARGETFOLDER);
foreach (string file in files)
System.IO.File.Delete(file);
string[] dirs = System.IO.Directory.GetDirectories(TARGETFOLDER);
foreach (string dir in dirs)
System.IO.Directory.Delete(dir, true);
}
int actualHeight = bmSource.Height;
int actualWidth = bmSource.Width;
if (((actualHeight % 256) != 0)
||
((actualWidth % 256) != 0))
{
Console.WriteLine("image width and height pixels should be multiples of 256");
return;
}
int actualResizeSizeWidth = 1;
int level = 0;
while (level <= maxZoom)
{
string leveldirectory = System.IO.Path.Combine(TARGETFOLDER, String.Format("{0}", level));
if (!System.IO.Directory.Exists(leveldirectory))
System.IO.Directory.CreateDirectory(leveldirectory);
int rowsInLevel = Convert.ToInt32(Math.Pow(2, level));
actualResizeSizeWidth = 256 * rowsInLevel;
//create image to parse
int actualResizeSizeHeight = (actualHeight * actualResizeSizeWidth) / actualWidth;
Bitmap resized = new Bitmap(bmSource, new Size(actualResizeSizeWidth, actualResizeSizeHeight));
string levelSourceImage = System.IO.Path.Combine(leveldirectory, "level.png");
resized.Save(levelSourceImage);
for (int x = 0; x < rowsInLevel; x++)
{
string levelrowdirectory = System.IO.Path.Combine(leveldirectory, String.Format("{0}", x));
if (!System.IO.Directory.Exists(levelrowdirectory))
System.IO.Directory.CreateDirectory(levelrowdirectory);
Bitmap bmLevelSource = (Bitmap)Bitmap.FromFile(levelSourceImage);
//generate tiles
int numberTilesHeight = Convert.ToInt32(Math.Ceiling(actualResizeSizeHeight / 256.0));
for (int y = 0; y < numberTilesHeight; y++)
{
Console.WriteLine("Generating Tiles " + level.ToString() + " " + x.ToString() + " " + y.ToString()); int heightToCrop = actualResizeSizeHeight >= 256 ? 256 : actualResizeSizeHeight;
Rectangle destRect = new Rectangle(x * 256, y * 256, 256, heightToCrop);
//croped
Bitmap bmTile = bmLevelSource.Clone(destRect, System.Drawing.Imaging.PixelFormat.DontCare);
//full tile
Bitmap bmFullTile = new Bitmap(256, 256);
Graphics gfx = Graphics.FromImage(bmFullTile);
gfx.DrawImageUnscaled(bmTile, 0, 0);
bmFullTile.Save(System.IO.Path.Combine(levelrowdirectory, String.Format("{0}.png", y)));
bmFullTile.Dispose();
bmTile.Dispose();
}
}
level++;
}
i comment the below code when i run the program
if (((actualHeight % 256) != 0)
||
((actualWidth % 256) != 0))
{
Console.WriteLine("image width and height pixels should be multiples of 256");
return;
}
what is the fault for which i got the error called "Out of Memory"
Thanks
Edit
actual image height and width was 1250 and 2500.
actualResizeSizeWidth 256
actualResizeSizeHeight 128
i include a panorama image url in this post at top. can u plzz download url and execute my code at your end to see memory issue is coming?
Code Update
i modify the code a bit and dispose some Bitmap.
dispose like this way
bmLevelSource.Dispose(); and resized.Dispose();
while (level <= maxZoom)
{
string leveldirectory = System.IO.Path.Combine(TARGETFOLDER, String.Format("{0}", level));
if (!System.IO.Directory.Exists(leveldirectory))
System.IO.Directory.CreateDirectory(leveldirectory);
int rowsInLevel = Convert.ToInt32(Math.Pow(2, level));
actualResizeSizeWidth = 256 * rowsInLevel;
//create image to parse
int actualResizeSizeHeight = (actualHeight * actualResizeSizeWidth) / actualWidth;
Bitmap resized = new Bitmap(bmSource, new Size(actualResizeSizeWidth, actualResizeSizeHeight));
string levelSourceImage = System.IO.Path.Combine(leveldirectory, "level.png");
resized.Save(levelSourceImage);
for (int x = 0; x < rowsInLevel; x++)
{
string levelrowdirectory = System.IO.Path.Combine(leveldirectory, String.Format("{0}", x));
if (!System.IO.Directory.Exists(levelrowdirectory))
System.IO.Directory.CreateDirectory(levelrowdirectory);
Bitmap bmLevelSource = (Bitmap)Bitmap.FromFile(levelSourceImage);
//generate tiles
int numberTilesHeight = Convert.ToInt32(Math.Ceiling(actualResizeSizeHeight / 256.0));
for (int y = 0; y < numberTilesHeight; y++)
{
Console.WriteLine("Generating Tiles " + level.ToString() + " " + x.ToString() + " " + y.ToString()); int heightToCrop = actualResizeSizeHeight >= 256 ? 256 : actualResizeSizeHeight;
Rectangle destRect = new Rectangle(x * 256, y * 256, 256, heightToCrop);
//croped
Bitmap bmTile = bmLevelSource.Clone(destRect, System.Drawing.Imaging.PixelFormat.DontCare);
//full tile
Bitmap bmFullTile = new Bitmap(256, 256);
Graphics gfx = Graphics.FromImage(bmFullTile);
gfx.DrawImageUnscaled(bmTile, 0, 0);
bmFullTile.Save(System.IO.Path.Combine(levelrowdirectory, String.Format("{0}.png", y)));
bmFullTile.Dispose();
bmTile.Dispose();
}
bmLevelSource.Dispose();
}
level++;
resized.Dispose();
}
please see my bit modified code and give suggestion now.
How do I save a generated thumbnail? I am getting this error:
Object reference not set to an instance of an object
This is my code. I am new to C#. I found the thumbnail generation code online and I thought I could use it but its giving me an error...
//1. <lcFilename> as path of large size file.
//2. <lnWidth> as width of required thumbnail.
//3. <lnHeight> as height of required thumbnail.
//The function returns a Bitmap object of the changed thumbnail image which you can save on the disk.
public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
{
System.Drawing.Bitmap bmpOut = null;
try
{
Bitmap loBMP = new Bitmap(lcFilename);
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 < lnWidth && loBMP.Height < lnHeight)
return loBMP;
if (loBMP.Width > loBMP.Height)
{
lnRatio = (decimal)lnWidth / loBMP.Width;
lnNewWidth = lnWidth;
decimal lnTemp = loBMP.Height * lnRatio;
lnNewHeight = (int)lnTemp;
}
else
{
lnRatio = (decimal)lnHeight / loBMP.Height;
lnNewHeight = lnHeight;
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;
}
// Thumbnail Generate
string largefilepath = "images/" + imageuploaded;
string largefilepath2 = "images/users/" + imageuploaded + "-160x160";
Bitmap bmp1 = new Bitmap(CreateThumbnail(largefilepath, 160, 160));
bmp1.Save(largefilepath2);
You have to Dispose your Graphics after it finishes its job. When you draw something on an image with Graphics, it is common to use using block but since it is already in the try/catch scope, it seems redundant here.
//1. <lcFilename> as path of large size file.
//2. <lnWidth> as width of required thumbnail.
//3. <lnHeight> as height of required thumbnail.
//The function returns a Bitmap object of the changed thumbnail image which you can save on the disk.
public static Bitmap CreateThumbnail(string lcFilename, int lnWidth, int lnHeight)
{
System.Drawing.Bitmap bmpOut = null;
try
{
Bitmap loBMP = new Bitmap(lcFilename);
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 < lnWidth && loBMP.Height < lnHeight)
return loBMP;
if (loBMP.Width > loBMP.Height)
{
lnRatio = (decimal)lnWidth / loBMP.Width;
lnNewWidth = lnWidth;
decimal lnTemp = loBMP.Height * lnRatio;
lnNewHeight = (int)lnTemp;
}
else
{
lnRatio = (decimal)lnHeight / loBMP.Height;
lnNewHeight = lnHeight;
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);
// Dispose Graphics so that it releases all the resources it's holding to draw on that image.
g.Dispose();
/* or you could use Graphics as below.. but it seems redundant, because it is already in the try / catch block.
using ( 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;
}
// Thumbnail Generate
string largefilepath = "images/" + imageuploaded;
string largefilepath2 = "images/users/" + imageuploaded + "-160x160";
Bitmap bmp1 = new Bitmap(CreateThumbnail(largefilepath, 160, 160));
bmp1.Save(largefilepath2);
The problem is you have a try..catch inside your method and this is swallowing the exception, and you are returning null from there, Hence the exception that you have reported.
Option 1
My suggestion is to either do something with the exception such as log it, this way you know something went wrong, like now. And handle the instance where a null value can be returned by the method, as follows:
string largefilepath = "images/" + imageuploaded;
string largefilepath2 = "images/users/" + imageuploaded + "-160x160";
Bitmap bmp1 = new Bitmap(CreateThumbnail(largefilepath, 160, 160));
if (bmp1 == null) {
// there was an exception, check the logs
}
else {
bmp1.Save(largefilepath2);
}
Option 2:
Or remove the try catch completely from the method and move it out as follows:
Note: the following code assumes you have removed the try...catch from the CreateThumbnail method.
try {
//Where imageUploaded is the name of the image with the extension, e.g. "samplePic.jpg"
string largefilepath = #"c:\images\" + imageuploaded;
string largefilepath2 = #"c:\images\users\" + System.IO.Path.GetFileNameWithoutExtension(imageuploaded) + "-160x160" + System.IO.Path.GetExtension(largefilepath);
Bitmap bmp1 = new Bitmap(CreateThumbnail(largefilepath, 160, 160));
bmp1.Save(largefilepath2);
}
catch (Exception ex) {
//do something with the exception
}
In the below code i am uploading a document My aim is if it is a image document i have to reduce its size to 20 kb.Pls help me to do this.
string Uploadpath = ConfigurationManager.AppSettings["SearchFolder"];
string strUploadpath = Uploadpath.TrimEnd("\\".ToCharArray()) + "\\" + strClientName + "\\" + strDocumentFolder + "\\";
DirectoryInfo dInfo = new DirectoryInfo(strUploadpath);
if (!dInfo.Exists)
{
dInfo.Create();
}
if (DocumentsUpload.FileName != null && DocumentsUpload.FileName != string.Empty)
{
DocumentsUpload.SaveAs((strUploadpath) + DocumentsUpload.FileName);
}
An image size depends on few factors (size, resolution, format, compression, etc) and there is no guarantee that you could reduce it in exactly 20 kb without losing the quality. In order to change size of the file you can try to save new image adjusting its properties such as CompositingQuality, InterpolationMode, and quality and compression. For example, CompositingQuality could be set to "HighSpeed" value, InterpolationMode to "Low", etc. It all depends on what kind of images you have and it needs to be tested.
Example
//DocumentsUpload.SaveAs((strUploadpath) + DocumentsUpload.FileName);
Stream stream = DocumentsUpload.PostedFile.InputStream;
Bitmap source = new Bitmap(stream);
Bitmap target = new Bitmap(source.Width, source.Height);
Graphics g = Graphics.FromImage(target);
EncoderParameters e;
g.CompositingQuality = CompositingQuality.HighSpeed; <-- here
g.InterpolationMode = InterpolationMode.Low; <-- here
Rectangle recCompression = new Rectangle(0, 0, source.Width, source.Height);
g.DrawImage(source, recCompression);
e = new EncoderParameters(2);
e.Param[0] = new EncoderParameter(Encoder.Quality, 70); <-- here 70% quality
e.Param[1] = new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionLZW); <-- here
target.Save(newName, GetEncoderInfo("image/jpeg"), e);
g.Dispose();
target.Dispose();
public static ImageCodecInfo GetEncoderInfo(string sMime)
{
ImageCodecInfo[] objEncoders;
objEncoders = ImageCodecInfo.GetImageEncoders();
for (int iLoop = 0; iLoop <= (objEncoders.Length - 1); iLoop++)
{
if (objEncoders[iLoop].MimeType == sMime)
return objEncoders[iLoop];
}
return null;
}
Hope this helps.
this example works for .Net 4.5+ and upload several images at time. Also resizes the size of the image dynamically according to the value of the variable MaxWidthHeight. Excuse my bad english.
Example
private void UploadResizeImage()
{
string codigo = "";
string dano = "";
string nav = "";
string nombreArchivo = "";
string extension = "";
int cont = 0;
int MaxWidthHeight = 1024; // This is the maximum size that the width or height file should have
int factorConversion = 0;
int newWidth = 0;
int newHeight = 0;
int porcExcesoImg = 0;
Bitmap newImage = null;
string directory = "dano";
System.Drawing.Image image = null;
string targetPath = "";
try
{
if (!String.IsNullOrEmpty(Request.QueryString["codigo"]) && !String.IsNullOrEmpty(Request.QueryString["dano"]) && !String.IsNullOrEmpty(Request.QueryString["nav"]))
{
codigo = Request.QueryString["codigo"].ToString();
dano = Request.QueryString["dano"].ToString();
nav = Request.QueryString["nav"].ToString();
Directory.CreateDirectory(Server.MapPath(directory));
Directory.CreateDirectory(Server.MapPath(directory + "/" + nav));
string fechaHora = DateTime.Now.ToString("yyyyMMdd-HHmmss");
nombreArchivo = codigo + "-" + dano + "-" + fechaHora;
string html = "<h4>Se cargaron con éxito estos archivos al servidor:</h4>";
if (UploadImages.HasFiles)
{
html += "<ul>";
foreach (HttpPostedFile uploadedFile in UploadImages.PostedFiles)
{
cont++;
extension = System.IO.Path.GetExtension(UploadImages.FileName);
targetPath = Server.MapPath("~/" + directory + "/" + nav + "/").ToString() + nombreArchivo + "-" + cont.ToString() + extension;
if (extension.ToLower() == ".png" || extension.ToLower() == ".jpg")
{
Stream strm = null;
strm = uploadedFile.InputStream;
//strm = UploadImages.PostedFile.InputStream;
using (image = System.Drawing.Image.FromStream(strm))
{
string size = image.Size.ToString();
int width = image.Width;
int height = image.Height;
if (width > MaxWidthHeight || height > MaxWidthHeight)
{
porcExcesoImg = (width * 100) / MaxWidthHeight; // excessive size in percentage
factorConversion = porcExcesoImg / 100;
newWidth = width / factorConversion;
newHeight = height / factorConversion;
newImage = new Bitmap(newWidth, newHeight);
var graphImage = Graphics.FromImage(newImage);
graphImage.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphImage.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphImage.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
var imgRectangle = new Rectangle(0, 0, newWidth, newHeight);
graphImage.DrawImage(image, imgRectangle);
newImage.Save(targetPath, image.RawFormat);
}
else
{
uploadedFile.SaveAs(targetPath);
}
html += "<li>" + String.Format("{0}", uploadedFile.FileName) + "</li>";
}
}
}
html += "</ul>";
listofuploadedfiles.Text = html;
}
else
{
listofuploadedfiles.Text = "No se ha selecionado ninguna imagen!";
}
}
else
{
listofuploadedfiles.Text = "No se recibieron los parámetros para poder cargar las imágenes!";
}
}
catch (Exception ex)
{
listofuploadedfiles.Text = ex.Message.ToString();
}
}
private void button4_Click(object sender, EventArgs e)
{
string originalPathFile = #"C:\Users\user\Downloads\CaptchaCollection\Small\Sorting\";
string newPathFile = #"C:\Users\user\Downloads\CaptchaCollection\Small\Sorted\";
bool endInner = false;
int count2 = 1;
while (!endInner)
{
var files = Directory.GetFiles(originalPathFile).Select(nameWithExtension => Path.GetFileNameWithoutExtension(nameWithExtension)).Where(name => { int number; return int.TryParse(name, out number); }).Select(name => int.Parse(name)).OrderBy(number => number).ToArray();
Bitmap im1 = new Bitmap(originalPathFile + files[0].ToString() + ".png");
Bitmap im2 = new Bitmap(originalPathFile + files[count2].ToString() + ".png");
if (compare(im1, im2))
{
// if it's equal
File.Move(originalPathFile + files[count2].ToString() + ".png", newPathFile + files[count2].ToString() + ".png");
MessageBox.Show(files[count2].ToString() + " was removed");
}
if (count2 >= files.Length - 1) // checks if reached last file in directory
{
endInner = true;
}
count2++;
}
}
This is my button that will move all visually duplicated images comparing the first index (will make a nested one to go to next image and so on later). I create 2 path file strings. Then I use a while loop just to check if my count has reached the amount of files in the directory. After that it will end the loop.
private bool compare(Bitmap bmp1, Bitmap bmp2)
{
bool equals = true;
Rectangle rect = new Rectangle(0, 0, bmp1.Width, bmp1.Height);
BitmapData bmpData1 = bmp1.LockBits(rect, ImageLockMode.ReadOnly, bmp1.PixelFormat);
BitmapData bmpData2 = bmp2.LockBits(rect, ImageLockMode.ReadOnly, bmp2.PixelFormat);
unsafe
{
byte* ptr1 = (byte*)bmpData1.Scan0.ToPointer();
byte* ptr2 = (byte*)bmpData2.Scan0.ToPointer();
int width = rect.Width * 3; // for 24bpp pixel data
for (int y = 0; equals && y < rect.Height; y++)
{
for (int x = 0; x < width; x++)
{
if (*ptr1 != *ptr2)
{
equals = false;
break;
}
ptr1++;
ptr2++;
}
ptr1 += bmpData1.Stride - width;
ptr2 += bmpData2.Stride - width;
}
}
bmp1.UnlockBits(bmpData1);
bmp2.UnlockBits(bmpData2);
return equals;
}
This method checks visually if an image is duplicated. Returns true if it is.
I'm getting this exception:
The process cannot access the file because it is being used by another process.
It occurred on this line:
File.Move(originalPathFile + files[count2].ToString() + ".png", newPathFile + files[count2].ToString() + ".png");
When you open file using new Bitmap(fileName) you can't move file because it is in use.
So dispose first that object and then try to move file. You can also use following approch where you can send filename instead of Bitmap and in compare function use using keywork which will automatically dispose object.
compare(originalPathFile + files[0].ToString() + ".png", originalPathFile + files[count2].ToString() + ".png")
private bool compare(String bmp1Path, String bmp2Path)
{
bool equals = true;
Rectangle rect = new Rectangle(0, 0, bmp1.Width, bmp1.Height);
using(Bitmap im1 = new Bitmap(bmp1Path)
{
using(Bitmap im2 = new Bitmap(bmp2Path)
{
BitmapData bmpData1 = bmp1.LockBits(rect, ImageLockMode.ReadOnly, bmp1.PixelFormat);
BitmapData bmpData2 = bmp2.LockBits(rect, ImageLockMode.ReadOnly, bmp2.PixelFormat);
unsafe
{
byte* ptr1 = (byte*)bmpData1.Scan0.ToPointer();
byte* ptr2 = (byte*)bmpData2.Scan0.ToPointer();
int width = rect.Width * 3; // for 24bpp pixel data
for (int y = 0; equals && y < rect.Height; y++)
{
for (int x = 0; x < width; x++)
{
if (*ptr1 != *ptr2)
{
equals = false;
break;
}
ptr1++;
ptr2++;
}
ptr1 += bmpData1.Stride - width;
ptr2 += bmpData2.Stride - width;
}
}
bmp1.UnlockBits(bmpData1);
bmp2.UnlockBits(bmpData2);
}
}
return equals;
}
how to create fixed size thumbnail dynamically and resize image in listview best fit the size of the thumbnail.
private void Treeview1_AfterSelect(System.Object sender, System.Windows.Forms.TreeViewEventArgs e)
{
if (folder != null && System.IO.Directory.Exists(folder))
{
try
{
DirectoryInfo dir = new DirectoryInfo(#folder);
foreach (FileInfo file in dir.GetFiles())
{
try
{
imageList.ImageSize = new Size(136, 136);
imageList.ColorDepth = ColorDepth.Depth32Bit;
Image img = new Bitmap(Image.FromFile(file.FullName));
Graphics g = Graphics.FromImage(img);
g.DrawRectangle(Pens.Red, 0, 0, img.Width - 21, img.Height - 21);
//g.DrawRectangle(Pens.Red, 0, 0, img.Width, img.Height);
imageList.Images.Add(img);
}
catch
{
Console.WriteLine("This is not an image file");
}
}
for (int j = 0; j < imageList.Images.Count; j++)
{
this.ListView1.Items.Add("Item" + j);
this.ListView1.Items[j].ImageIndex = j;
}
this.ListView1.View = View.LargeIcon;
this.ListView1.LargeImageList = imageList;
//this.ListView1.DrawItem += new DrawListViewItemEventHandler(ListView1_DrawItem);
//import(folder);
}
catch (Exception ex)
{
}
}
I have code in this answer specifically for resizing images along with resolution:
public void GenerateThumbNail(HttpPostedFile fil, string sPhysicalPath,
string sOrgFileName,string sThumbNailFileName,
ImageFormat oFormat, int rez)
{
try
{
System.Drawing.Image oImg = System.Drawing.Image.FromStream(fil.InputStream);
decimal pixtosubstract = 0;
decimal percentage;
//default
Size ThumbNailSizeToUse = new Size();
if (ThumbNailSize.Width < oImg.Size.Width || ThumbNailSize.Height < oImg.Size.Height)
{
if (oImg.Size.Width > oImg.Size.Height)
{
percentage = (((decimal)oImg.Size.Width - (decimal)ThumbNailSize.Width) / (decimal)oImg.Size.Width);
pixtosubstract = percentage * oImg.Size.Height;
ThumbNailSizeToUse.Width = ThumbNailSize.Width;
ThumbNailSizeToUse.Height = oImg.Size.Height - (int)pixtosubstract;
}
else
{
percentage = (((decimal)oImg.Size.Height - (decimal)ThumbNailSize.Height) / (decimal)oImg.Size.Height);
pixtosubstract = percentage * (decimal)oImg.Size.Width;
ThumbNailSizeToUse.Height = ThumbNailSize.Height;
ThumbNailSizeToUse.Width = oImg.Size.Width - (int)pixtosubstract;
}
}
else
{
ThumbNailSizeToUse.Width = oImg.Size.Width;
ThumbNailSizeToUse.Height = oImg.Size.Height;
}
Bitmap bmp = new Bitmap(ThumbNailSizeToUse.Width, ThumbNailSizeToUse.Height);
bmp.SetResolution(rez, rez);
System.Drawing.Image oThumbNail = bmp;
bmp = null;
Graphics oGraphic = Graphics.FromImage(oThumbNail);
oGraphic.CompositingQuality = CompositingQuality.HighQuality;
oGraphic.SmoothingMode = SmoothingMode.HighQuality;
oGraphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
Rectangle oRectangle = new Rectangle(0, 0, ThumbNailSizeToUse.Width, ThumbNailSizeToUse.Height);
oGraphic.DrawImage(oImg, oRectangle);
oThumbNail.Save(sPhysicalPath + sThumbNailFileName, oFormat);
oImg.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}