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);
}
}
Related
I am trying to create a big final jpg image from 4 different jpg images. I noticed after adding images onto the final image, the size of the image changes.
The size of the image should remain the same on the final image too.
Ex- The galaxy image(dark sky) on the final image looks small, compared to the actual image.
Any help would be appreciated.
private void CombineImages()
{
string path1 = #"C:\temp\";
DirectoryInfo directory = new DirectoryInfo(path1);
//change the location to store the final image.
FileInfo[] files = directory.GetFiles();
string finalImage = #"C:\\images\\FinalImage3.jpg";
List<int> imageHeights = new List<int>();
List<int> imagewidths = new List<int>();
int nIndex = 0;
int width = 0;
int maxHeight = 0;
int totalHeight = 0;
bool odd = true;
bool firstRow = true;
//to get height and width to create final image
foreach (FileInfo file in files)
{
if (odd)
{
if (firstRow)
{
Image img = Image.FromFile(file.FullName);
firstRow = false;
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
odd = false;
}
else
{
Image img = Image.FromFile(file.FullName);
maxHeight = imageHeights.Max();
imagewidths.Add(width+100);
width = 0;
totalHeight = totalHeight + maxHeight+img.Height+100;
imageHeights.Clear();
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
odd = false;
}
}
else
{
Image img = Image.FromFile(file.FullName);
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
odd = true;
}
}
imageHeights.Sort();
Bitmap img3 = new Bitmap(imagewidths.Max(), totalHeight);
Graphics g = Graphics.FromImage(img3);
g.Clear(Color.Gainsboro);
imageHeights = new List<int>();
imagewidths = new List<int>();
nIndex = 0;
width = 0;
maxHeight = 0;
totalHeight = 0;
odd = true;
firstRow = true;
int imagewidth = 0;
//actual merging of images
foreach (FileInfo file in files)
{
Image img = Image.FromFile(file.FullName);
if (odd)
{
if (firstRow)
{
g.DrawImage(img, 25, 25);
firstRow = false;
imageHeights.Add(img.Height);
width += img.Width;
img.Dispose();
odd = false;
}
else
{
maxHeight = imageHeights.Max();
g.DrawImage(img, 25, maxHeight+50);
imagewidths.Add(width);
width = 0;
totalHeight = totalHeight + maxHeight + img.Height;
imageHeights.Clear();
imageHeights.Add(img.Height);
width += img.Width;
imagewidth = img.Width;
img.Dispose();
odd = false;
}
}
else
{
imageHeights.Add(img.Height);
g.DrawImage(img, width+50, maxHeight+50);
img.Dispose();
odd = true;
}
img.Dispose();
}
g.Dispose();
System.Drawing.Imaging.Encoder myEncoder =
System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 50L);
myEncoderParameters.Param[0] = myEncoderParameter;
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
img3.Save(finalImage, jpgEncoder, myEncoderParameters);
img3.Dispose();
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
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();
}
}
It happen only when I resize the form when the program is running.
I click the "-" and the program is minimised to the taskbar, then I see the error/exception message.
protected override void OnLayout(LayoutEventArgs levent)
{
base.OnLayout(levent);
if (!_addingLines)
SplitText(this.Text);
if (_backBmpBU != null)
this._backBmp = MakeBackBmp(_backBmpBU);
if (this.BitmapModus)
{
UpdateBitmap();
}
}
private void UpdateBitmap()
{
if (_lines != null && _lines.Length > 0)
{
SizeF sz = new SizeF(0, 0);
float lineOrigHeight = sz.Height;
using (Graphics g = this.CreateGraphics())
{
sz = g.MeasureString("Teststring", this.Font);
if (this._additionalSpaceBetweenLines > 0)
sz = new SizeF(sz.Width, sz.Height + this._additionalSpaceBetweenLines);
}
this._textHeight = sz.Height * _lines.Length;
if (_bmp != null)
{
_bmp.Dispose();
_bmp = null;
}
try
{
if (this._textHeight > MAXHEIGHT)
throw new Exception("Text too long, for BitmapMode.");
_bmp = new Bitmap(this.ClientSize.Width, (int)Math.Ceiling(this._textHeight));
using (Graphics g = Graphics.FromImage(_bmp))
{
//set it to value you like...
g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAliasGridFit;
g.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.None;
using (SolidBrush b = new SolidBrush(this.ForeColor))
{
for (int i = 0; i < _lines.Length; i++)
{
SolidBrush bb = b;
if (TrimText)
_lines[i] = _lines[i].Trim();
sz = g.MeasureString(_lines[i], this.Font);
lineOrigHeight = sz.Height;
if (this._additionalSpaceBetweenLines > 0)
sz = new SizeF(sz.Width, sz.Height + this._additionalSpaceBetweenLines);
_posX = 0;
if (this.TextLayoutCentered)
_posX = (this.ClientSize.Width - sz.Width) / 2.0F;
bool drect = false;
bool colw = false;
int indx = -1;
int length = 0;
string textToFind = "";
Color fc = this.ForeColor;
Color bc = Color.Transparent;
Color rc = Color.Transparent;
if (Words != null && Words.Count > 0)
{
for (int ii = 0; ii < Words.Count; ii++)
{
if (_lines[i].Contains(Words[ii].WordOrText))
{
bb = new SolidBrush(Words[ii].ForeColor);
if (Words[ii].DrawRect)
drect = true;
if (Words[ii].ColorOnlyThisWord)
colw = true;
indx = _lines[i].IndexOf(Words[ii].WordOrText);
length = Words[ii].WordOrText.Length;
textToFind = Words[ii].WordOrText;
fc = Words[ii].ForeColor;
bc = Words[ii].BackColor;
rc = Words[ii].RectColor;
drect = Words[ii].DrawRect;
}
}
}
if (colw)
{
//reset b and create a new color brush
if (bb.Equals(b) == false)
bb.Dispose();
bb = b;
string ftext = _lines[i];
float cPosX = _posX;
using (SolidBrush bbb = new SolidBrush(fc))
{
while (indx > -1)
{
if (indx > 0)
g.DrawString(ftext.Substring(0, indx), this.Font, bb, new PointF(cPosX, sz.Height * i + _additionalSpaceBetweenLines / 2F));
cPosX += g.MeasureString(ftext.Substring(0, indx), this.Font).Width;
SizeF sfWord = g.MeasureString(ftext.Substring(indx, length), this.Font);
if (bc.ToArgb().Equals(Color.Transparent.ToArgb()) == false)
{
using (SolidBrush bbbb = new SolidBrush(bc))
g.FillRectangle(bbbb, cPosX, sz.Height * i + _additionalSpaceBetweenLines / 2F, sfWord.Width, sfWord.Height);
}
g.DrawString(ftext.Substring(indx, length), this.Font, bbb, new PointF(cPosX, sz.Height * i + _additionalSpaceBetweenLines / 2F));
cPosX += sfWord.Width;
ftext = ftext.Substring(indx + length);
if (textToFind.Length > 0)
indx = ftext.IndexOf(textToFind);
else
indx = -1;
}
if (ftext.Length > 0)
g.DrawString(ftext, this.Font, bb, new PointF(cPosX, sz.Height * i + _additionalSpaceBetweenLines / 2F));
}
}
else
{
if (bc.ToArgb().Equals(Color.Transparent.ToArgb()) == false)
{
using (SolidBrush bbbb = new SolidBrush(bc))
g.FillRectangle(bbbb, _posX, sz.Height * i + _additionalSpaceBetweenLines / 2F, sz.Width, lineOrigHeight);
}
g.DrawString(_lines[i], this.Font, bb, new PointF(_posX, sz.Height * i + _additionalSpaceBetweenLines / 2F));
}
if (drect)
{
if (rc.ToArgb().Equals(Color.Transparent.ToArgb()) == false)
using (Pen p = new Pen(rc))
g.DrawRectangle(p, _posX, sz.Height * i + _additionalSpaceBetweenLines / 2F, sz.Width, lineOrigHeight);
}
if (bb.Equals(b) == false)
bb.Dispose();
if (DrawRect)
{
using (Pen p = new Pen(this.ForeColor))
{
if (DrawRectAroundText)
g.DrawRectangle(p, _posX, sz.Height * i + _additionalSpaceBetweenLines / 2F, sz.Width, lineOrigHeight);
else
g.DrawRectangle(p, 0, sz.Height * i + _additionalSpaceBetweenLines / 2F, this.ClientSize.Width - 1, lineOrigHeight);
}
}
}
}
}
}
catch (Exception ex)
{
if (_bmp != null)
{
_bmp.Dispose();
_bmp = null;
}
this.BitmapModus = false;
//MessageBox.Show(ex.Message + " switching to Dynamic-Draw-Mode.");
OnSwitchModeOnError();
}
}
}
When the program is running and i minimize the form to the taskbar im getting exception:
Parameter is not valid
The full exception message:
System.ArgumentException was caught
HResult=-2147024809
Message=Parameter is not valid.
Source=System.Drawing
StackTrace:
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height, PixelFormat format)
at System.Drawing.Bitmap..ctor(Int32 width, Int32 height)
at ScrollLabelTest.ScrollLabel.UpdateBitmap() in e:\scrolllabel\ScrollLabel\ScrollLabel\ScrollLabel.cs:line 601
InnerException:
I had the same problem, with a huge list of errors in the Just-In-Time-Debugger. After several hours of searching I found my own way. Try this, no more exceptions!!
private void picMinimize_Click(object sender, EventArgs e)
{
try
{
panelUC.Visible = false; //change visible status of your form, etc.
this.WindowState = FormWindowState.Minimized; //minimize
minimizedFlag = true; //set a global flag
}
catch (Exception)
{
}
}
private void mainForm_Resize(object sender, EventArgs e)
{
//check if form is minimized, and you know that this method is only called if and only if the form get a change in size, meaning somebody clicked in the taskbar on your application
if (minimizedFlag == true)
{
panelUC.Visible = true; //make your panel visible again! thats it
minimizedFlag = false; //set flag back
}
}
Thumb up!
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);
I want to print one tall (long) image in many pages. So in every page, I take a suitable part from the image and I draw it in the page.
the problem is that I have got the image shrunk (its shape is compressed) in the page,so I added an scale that its value is 1500 .
I think that I can solve the problem if I knew the height of the page (e.Graphics) in pixels.
to convert Inches to Pixel, Do I have to multiply by (e.Graphics.DpiX = 600) or multiply by 96 .
void printdocument_PrintPage(object sender, PrintPageEventArgs e)
{
if (pageImage == null)
return;
e.Graphics.PageUnit = GraphicsUnit.Pixel;
e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
e.Graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
float a = (e.MarginBounds.Width / 100) * e.Graphics.DpiX;
float b = ((e.MarginBounds.Height / 100) * e.Graphics.DpiY);
int scale = 1500;
scale = 0; //try to comment this
RectangleF srcRect = new RectangleF(0, startY, pageImage.Width, b - scale);
RectangleF destRect = new RectangleF(0, 0, a, b);
e.Graphics.DrawImage(pageImage, destRect, srcRect, GraphicsUnit.Pixel);
startY = Convert.ToInt32(startY + b - scale);
e.HasMorePages = (startY < pageImage.Height);
}
could you please make it works correctly.
you can download the source code from (here).
thanks in advanced.
I tried to complete your task.
Here you go. Hope it helps.
This method prints the image on several pages (or one if image is small).
private void printImage_Btn_Click(object sender, EventArgs e)
{
list = new List<Image>();
Graphics g = Graphics.FromImage(image_PctrBx.Image);
Brush redBrush = new SolidBrush(Color.Red);
Pen pen = new Pen(redBrush, 3);
decimal xdivider = image_PctrBx.Image.Width / 595m;
int xdiv = Convert.ToInt32(Math.Ceiling(xdivider));
decimal ydivider = image_PctrBx.Image.Height / 841m;
int ydiv = Convert.ToInt32(Math.Ceiling(ydivider));
/*int xdiv = image_PctrBx.Image.Width / 595; //This is the xsize in pt (A4)
int ydiv = image_PctrBx.Image.Height / 841; //This is the ysize in pt (A4)
// # 72 dots-per-inch - taken from Adobe Illustrator
if (xdiv >= 1 && ydiv >= 1)
{*/
for (int i = 0; i < xdiv; i++)
{
for (int y = 0; y < ydiv; y++)
{
Rectangle r;
try
{
r = new Rectangle(i * Convert.ToInt32(image_PctrBx.Image.Width / xdiv),
y * Convert.ToInt32(image_PctrBx.Image.Height / ydiv),
image_PctrBx.Image.Width / xdiv,
image_PctrBx.Image.Height / ydiv);
}
catch (Exception)
{
r = new Rectangle(i * Convert.ToInt32(image_PctrBx.Image.Width / xdiv),
y * Convert.ToInt32(image_PctrBx.Image.Height),
image_PctrBx.Image.Width / xdiv,
image_PctrBx.Image.Height);
}
g.DrawRectangle(pen, r);
list.Add(cropImage(image_PctrBx.Image, r));
}
}
g.Dispose();
image_PctrBx.Invalidate();
image_PctrBx.Image = list[0];
PrintDocument printDocument = new PrintDocument();
printDocument.PrintPage += PrintDocument_PrintPage;
PrintPreviewDialog previewDialog = new PrintPreviewDialog();
previewDialog.Document = printDocument;
pageIndex = 0;
previewDialog.ShowDialog();
// don't forget to detach the event handler when you are done
printDocument.PrintPage -= PrintDocument_PrintPage;
}
This method prints every picture in the List in the needed dimensions (A4 size):
private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
// Draw the image for the current page index
e.Graphics.DrawImageUnscaled(list[pageIndex],
e.PageBounds.X,
e.PageBounds.Y);
// increment page index
pageIndex++;
// indicate whether there are more pages or not
e.HasMorePages = (pageIndex < list.Count);
}
This method crops the image and returns every part of the image:
private static Image cropImage(Image img, Rectangle cropArea)
{
Bitmap bmpImage = new Bitmap(img);
Bitmap bmpCrop = bmpImage.Clone(cropArea, System.Drawing.Imaging.PixelFormat.DontCare);
return (Image)(bmpCrop);
}
The Image gets loaded from the PictureBox, so make sure the image is loaded. (No exception handling yet).
internal string tempPath { get; set; }
private int pageIndex = 0;
internal List<Image> list { get; set; }
These variables are defined as global variables.
You can download a sample project here:
http://www.abouchleih.de/projects/PrintImage_multiplePages.zip // OLD Version
http://www.abouchleih.de/projects/PrintImage_multiplePages_v2.zip // NEW
I have Created a Class file for multiple page print a single large image.
Cls_PanelPrinting.Print Print =new Cls_PanelPrinting.Print(PnlContent/Image);
You have to Pass the panel or image.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Printing;
namespace Cls_PanelPrinting
{
public class Print
{
readonly PrintDocument printdoc1 = new PrintDocument();
readonly PrintPreviewDialog previewdlg = new PrintPreviewDialog();
public int page = 1;
internal string tempPath { get; set; }
private int pageIndex = 0;
internal List<Image> list { get; set; }
private int _Line = 0;
private readonly Panel panel_;
public Print(Panel pnl)
{
panel_ = pnl;
printdoc1.PrintPage += (printdoc1_PrintPage);
PrintDoc();
}
private void printdoc1_PrintPage(object sender, PrintPageEventArgs e)
{
Font myFont = new Font("Cambria", 10, FontStyle.Italic, GraphicsUnit.Point);
float lineHeight = myFont.GetHeight(e.Graphics) + 4;
float yLineTop = 1000;
int x = e.MarginBounds.Left;
int y = 25; //e.MarginBounds.Top;
e.Graphics.DrawImageUnscaled(list[pageIndex],
x,y);
pageIndex++;
e.HasMorePages = (pageIndex < list.Count);
e.Graphics.DrawString("Page No: " + pageIndex, myFont, Brushes.Black,
new PointF(e.MarginBounds.Right, yLineTop));
}
public void PrintDoc()
{
try
{
Panel grd = panel_;
Bitmap bmp = new Bitmap(grd.Width, grd.Height, grd.CreateGraphics());
grd.DrawToBitmap(bmp, new Rectangle(0, 0, grd.Width, grd.Height));
Image objImage = (Image)bmp;
Bitmap objBitmap = new Bitmap(objImage, new Size(700, objImage.Height));
Image PrintImage = (Image)objBitmap;
list = new List<Image>();
Graphics g = Graphics.FromImage(PrintImage);
Brush redBrush = new SolidBrush(Color.Red);
Pen pen = new Pen(redBrush, 3);
decimal xdivider = panel_.Width / 595m;
// int xdiv = Convert.ToInt32(Math.Ceiling(xdivider));
decimal ydivider = panel_.Height / 900m;
int ydiv = Convert.ToInt32(Math.Ceiling(ydivider));
int xdiv = panel_.Width / 595; //This is the xsize in pt (A4)
for (int i = 0; i < xdiv; i++)
{
for (int y = 0; y < ydiv; y++)
{
Rectangle r;
if (panel_.Height > 900)
{
try
{
if (list.Count > 0)
{
r = new Rectangle(0, (900 * list.Count), PrintImage.Width, PrintImage.Height - (900 * list.Count));
}
else
{
r = new Rectangle(0, 0, PrintImage.Width, 900);
}
list.Add(cropImage(PrintImage, r));
}
catch (Exception)
{
list.Add(PrintImage);
}
}
else { list.Add(PrintImage); }
}
}
g.Dispose();
PrintImage = list[0];
PrintDocument printDocument = new PrintDocument();
printDocument.PrintPage += printdoc1_PrintPage;
PrintPreviewDialog previewDialog = new PrintPreviewDialog();
previewDialog.Document = printDocument;
pageIndex = 0;
printDocument.DefaultPageSettings.PrinterSettings.PrintToFile = true;
string path = "d:\\BillIng.xps";
if (File.Exists(path))
File.Delete(path);
printDocument.DefaultPageSettings.PrinterSettings.PrintFileName = "d:\\BillIng.xps";
printDocument.PrintController = new StandardPrintController();
printDocument.Print();
printDocument.PrintPage -= printdoc1_PrintPage;
}
catch { }
}
private static Image cropImage(Image img, Rectangle cropArea)
{
Bitmap bmpImage = new Bitmap(img);
Bitmap bmpCrop = bmpImage.Clone(cropArea, System.Drawing.Imaging.PixelFormat.DontCare);
return (Image)(bmpCrop);
}
}
}