I am converting number of Jpeg or Png image to PDF using iTextSharp dll. I can convert but the size of the PDF cause much worry. If I convert 9 jpeg images (total size is 4.5 MB) into single pdf , it creates 12.3 MB size of PDF. Below is conversion part.
private bool CreatePdf(string stFilePath_in, List<ImageData> lstImageData_in, string doctype, string stproCompid)
{
bool flag = false;
StringBuilder builder = new StringBuilder();
try
{
this.UtilityProgress(lstImageData_in.Count);
builder.Append(stFilePath_in);
builder.Append(#"\");
builder.Append(lstImageData_in[0].Barcode);
builder.Append(".pdf");
Document document = new Document(PageSize.LETTER, 10f, 10f, 42f, 35f);
PdfWriter.GetInstance(document, new FileStream(builder.ToString(), FileMode.OpenOrCreate));
document.Open();
IOrderedEnumerable<ImageData> enumerable = from files in lstImageData_in
orderby files.PageNo
select files;
if (enumerable != null)
{
DbFileData data2;
foreach (ImageData data in enumerable)
{
Bitmap bitmap = new Bitmap(data.FilePath);
iTextSharp.text.Image instance = iTextSharp.text.Image.GetInstance(bitmap, ImageFormat.Png);
if (instance.Height > instance.Width)
{
float num = 0f;
num = 700f / instance.Height;
instance.ScalePercent(num * 100f);
}
else
{
float num2 = 0f;
num2 = 540f / instance.Width;
instance.ScalePercent(num2 * 100f);
}
instance.Border = 15;
instance.BorderColor = BaseColor.BLACK;
instance.BorderWidth = 3f;
document.Add(instance);
document.NewPage();
bitmap.Dispose();
}
document.Close();
if (doctype == "AR")
{
//data2.m_stInvoiceNo = lstImageData_in[0].Barcode.Substring(2);
data2.m_stInvoiceNo = lstImageData_in[0].Barcode.ToString();
data2.m_doctype = "AR";
}
else
{
data2.m_stInvoiceNo = lstImageData_in[0].Barcode.ToString();
data2.m_doctype = "PO";
}
data2.m_stImgLocation = builder.ToString();
string str = DateTime.Now.ToString("MM/dd/yy,hh:mm:ss");
data2.m_dtDate = DateTime.Now.Date;
data2.m_stTime = str.Substring(str.IndexOf(",") + 1);
data2.m_stcompid = stproCompid;
this.OnPdfFileCreationCompleted(data2);
return true;
}
flag = false;
}
catch (Exception exception)
{
flag = false;
StringBuilder builder2 = new StringBuilder();
builder2.Append(builder.ToString());
builder2.Append(": \t");
builder2.Append(exception.Message);
this.m_excepLogger.LogException(builder2.ToString());
}
return flag;
}
The OP creates the iTextSharp Image object like this:
Bitmap bitmap = new Bitmap(data.FilePath);
iTextSharp.text.Image instance = iTextSharp.text.Image.GetInstance(bitmap, ImageFormat.Png);
What this actually means is that the original image file is decoded into a bitmap, and then iTextSharp is asked to use the bitmap as if it was a PNG image.
In case of JPG images this usually means that the amount of data required to store the image explodes.
To prevent such size explosions one should allow iTextSharp to directly work with the original image file data, in the context at hand:
iTextSharp.text.Image instance = iTextSharp.text.Image.GetInstance(data.FilePath);
Related
I need to extract images from PDF.
I know that some images are rotated 90 degrees (I checked with online tools).
I'm using this code:
PdfRenderListener:
public class PdfRenderListener : IExtRenderListener
{
// other methods ...
public void RenderImage(ImageRenderInfo renderInfo)
{
try
{
var mtx = renderInfo.GetImageCTM();
var image = renderInfo.GetImage();
var fillColor = renderInfo.GetCurrentFillColor();
var color = Color.FromArgb(fillColor?.RGB ?? Color.Empty.ToArgb());
var fileType = image.GetFileType();
var extension = "." + fileType;
var bytes = image.GetImageAsBytes();
var height = mtx[Matrix.I22];
var width = mtx[Matrix.I11];
// rotated image
if (height == 0 && width == 0)
{
var h = Math.Abs(mtx[Matrix.I12]);
var w = Math.Abs(mtx[Matrix.I21]);
}
// save image
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
When I save images with this code the rotated images are saved with distortion.
I have read this post iText 7 ImageRenderInfo Matrix contains negative height on Even number Pages and mkl answer.
In current transfromation matrix (mtx) I have these values:
0
841.9
0
-595.1
0
0
595.1
0
1
I know image rotated 90 degrees. How can I transform an image to get a normal image?
As #mkl mentioned, the true reason was not in the rotation of the image, but with the applied filter.
I analyzed the pdf file with iText RUPS and found that the image was encoded with a CCITTFaxDecode filter:
RUPS screen
Next, I looked for ways to decode this filter and found these questions
Extracting image from PDF with /CCITTFaxDecode filter.
How to use Bit Miracle LibTiff.Net to write the image to a MemoryStream
I used the BitMiracle.LibTiff.NET library
I wrote this method:
private byte[] DecodeInternal(byte[] rawBytes, int width, int height, int k, int bitsPerComponent)
{
var compression = GetCompression(k);
using var ms = new MemoryStream();
var tms = new TiffStream();
using var tiff = Tiff.ClientOpen("in-memory", "w", ms, tms);
tiff.SetField(TiffTag.IMAGEWIDTH, width);
tiff.SetField(TiffTag.IMAGELENGTH, height);
tiff.SetField(TiffTag.COMPRESSION, compression);
tiff.SetField(TiffTag.BITSPERSAMPLE, bitsPerComponent);
tiff.SetField(TiffTag.SAMPLESPERPIXEL, 1);
var writeResult = tiff.WriteRawStrip(0, rawBytes, rawBytes.Length);
if (writeResult == -1)
{
Console.WriteLine("Decoding error");
}
tiff.CheckpointDirectory();
var decodedBytes = ms.ToArray();
tiff.Close();
return decodedBytes;
}
private Compression GetCompression(int k)
{
return k switch
{
< 0 => Compression.CCITTFAX4,
0 => Compression.CCITTFAX3,
_ => throw new NotImplementedException("K > 0"),
};
}
After decoding and rotating the image, I was able to save a normal image. Thanks everyone for the help.
You can try this. I'm using Itext 7 for java. Here you still need to write your own listener:
public class MyImageRenderListener implements IEventListener {
protected String path;
protected String extension;
public MyImageRenderListener (String path) {
this.path = path;
}
public void eventOccurred(IEventData data, EventType type) {
switch (type) {
case RENDER_IMAGE:
try {
String filename;
FileOutputStream os;
ImageRenderInfo renderInfo = (ImageRenderInfo) data;
PdfImageXObject image = renderInfo.getImage();
if (image == null) {
return;
}
byte[] imageByte = image.getImageBytes(true);
extension = image.identifyImageFileExtension();
filename = String.format(path, image.getPdfObject().getIndirectReference().getObjNumber(), extension);
os = new FileOutputStream(filename);
os.write(imageByte);
os.flush();
os.close();
} catch (com.itextpdf.io.exceptions.IOException | IOException e) {
System.out.println(e.getMessage());
}
break;
default:
break;
}
}
public Set<EventType> getSupportedEvents() {
return null;
}
}
I checked for a pdf with a random rotation angle, and 90 degrees, the resulting picture was obtained without distortion
public void manipulatePdf() throws IOException, SQLException, ParserConfigurationException, SAXException {
PdfDocument pdfDoc = new PdfDocument(new PdfReader("path to pdf"), new PdfWriter(new ByteArrayOutputStream()));
MyImageRenderListener listener = new MyImageRenderListener("path to resulting image");
PdfCanvasProcessor parser = new PdfCanvasProcessor(listener);
for (int i = 1; i <= pdfDoc.getNumberOfPages(); i++) {
parser.processPageContent(pdfDoc.getPage(i));
}
pdfDoc.close();
}
Bitmap Image Multiplication
I Found this Memory stream option to merge the files with given no of repeats.
All the things are working file but in the End, the generated BMP file is not as per enter repetition.
Need help.
Commented lines in code is another way which I tried.
enter code here
public partial class Form1 : Form
{
FileStream bitmapfileload;
Bitmap bmp;
int NoOfRepeats;
public Form1()
{
InitializeComponent();
}
private void btnOpenFile_Click(object sender, EventArgs e)
{
DoubleBuffered = true;
OpenFileDialog openFileDialog1 = new OpenFileDialog
{
InitialDirectory = #"D:\",
Title = "Browse Design Files",
CheckFileExists = true,
CheckPathExists = true,
DefaultExt = "tif",
Filter = "Images (*.BMP;*.TIF)|*.BMP;*.TIF|" + "All files (*.*)|*.*",
FilterIndex = 1,
RestoreDirectory = true,
Multiselect = false,
ReadOnlyChecked = false,
ShowReadOnly = true
};
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
byte[] ba = null;
foreach (String file in openFileDialog1.FileNames)
{
Image temp = new Bitmap(file);
LblSourceWidth.Text = Convert.ToString(temp.Width);
LblSourHeight.Text = Convert.ToString(temp.Height);
temp.Dispose();
bitmapfileload = new FileStream(file,FileMode.Open,FileAccess.Read,FileShare.ReadWrite);
ba = streamToByteArray(bitmapfileload);
}
NoOfRepeats = int.Parse(ltbRepeat.Text); // Text box will give no of repeat for writing proceedure
// List <byte[]> ListBa = new List<byte[]>();
MemoryStream MergeFile = new MemoryStream();
using (MemoryStream allFrameStream = new MemoryStream())
{
for (int i = 0; i < NoOfRepeats; i++)
{
allFrameStream.Write(ba, 0, ba.Length);
allFrameStream.Position = ba.Length * i;
//ListBa.Add(allFrameStream.ToArray());
//ListBa.Add(ba);
}
MergeFile = allFrameStream;
bmp = new Bitmap(MergeFile);
}
//byte[] finaleba = Combine(ListBa.ToArray());
//byte[] finaleba = ListBa.Cast<byte[]>().SelectMany(a => a).ToArray();
//LblListCount.Text = Convert.ToString(finaleba.Length); // List Count = no of repeats for FOR-LOOP
//Stream Finalfile = new MemoryStream(MergeFile);
//richTextBox1.Text = Convert.ToString(Finalfile);
LblDestiWidth.Text = Convert.ToString(bmp.Width); // no change here
LblDestiHeight.Text = Convert.ToString(bmp.Height); // no change here
pictureBox1.Image = bmp;
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
}
}
private static byte[] Combine(byte[][] arrays)
{
byte[] bytes = new byte[arrays.Sum(a => a.Length)];
int offset = 0;
foreach (byte[] array in arrays)
{
Buffer.BlockCopy(array, 0, bytes, offset, array.Length);
offset += array.Length;
}
return bytes;
}
public static byte[] streamToByteArray(Stream input)
{
MemoryStream ms = new MemoryStream();
input.CopyTo(ms);
return ms.ToArray();
}
The example is not very obvious. I would assume the end goal is to produce a larger image, with multiple copies of the source image stacked on top of each other.
It looks like you are trying to do this by concatenating the streams for an image. This will not work since images have headers. This will cause only the first image to be decoded.
The correct approach would be to create a new, larger, bitmap, and copy all the pixel-values to this bitmap. For example:
public static unsafe Bitmap Repeat(Bitmap source, int count)
{
var targetHeight = source.Height * count;
var target = new Bitmap(source.Width, targetHeight, source.PixelFormat);
var sourceData = source.LockBits(new Rectangle(0,0, source.Width, source.Height), ImageLockMode.ReadOnly, source.PixelFormat);
var targetData = target.LockBits(new Rectangle(0, 0, target.Width, target.Height), ImageLockMode.ReadOnly,
target.PixelFormat);
try
{
var frameLength = sourceData.Stride * sourceData.Height;
for (int i = 0; i < count; i++)
{
var targetPtr = targetData.Scan0 + i * frameLength;
Buffer.MemoryCopy(sourceData.Scan0.ToPointer(), targetPtr.ToPointer(), frameLength * count, frameLength);
}
}
finally
{
source.UnlockBits(sourceData);
target.UnlockBits(targetData);
}
return target;
}
This could be adopted to merge images of different size, but it would require copying the image row by row instead, and some more math regarding height, indices etc. Note that this code is untested, use at own risk.
Another approach would be to use the Graphics api with FromImage and DrawImageUnscaled. This would perhaps be easier if you have multiple images.
I am creating a PDF in MVC project using iTextSharp on .NET platform. I am sending a HTML div in "Download PDF" function and adding image from c# code using iTextSharp classes, but now I want to add an Image on 3rd page but unfortunately I am unable to do that. Please help me.
Please find the below code that I wrote for adding image on first page, last page and a loop for adding image on each page... (BUT I CAN NOT ADD AN IMAGE ONLY ON 3RD PAGE)...
using (MemoryStream stream = new System.IO.MemoryStream())
{
string Grid = GridHtml.Replace("<br>", "\n\r");
StringReader sr = new StringReader(Grid);
iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(PageSize.A4, 10f, 10f, 100f, 0f);
pdfDoc.SetMargins(50f, 50f, 90f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
MyEvent events = new MyEvent();
writer.PageEvent = events;
pdfDoc.Open();
string imageURL1 = Server.MapPath("~/UploadedFiles/Calibehr.png");
iTextSharp.text.Image jpg12 = iTextSharp.text.Image.GetInstance(imageURL1);
////Resize image depend upon your need
jpg12.ScaleToFit(140f, 120f);
jpg12.SpacingBefore = 10f;
//////Give some space after the image
jpg12.SpacingAfter = 1f;
jpg12.Alignment = Element.ALIGN_CENTER;
jpg12.SetAbsolutePosition(40, 750);
pdfDoc.Add(jpg12);
if ((fc["hdnFormatType"] != "ManageService"))
{
string imageURL3 = Server.MapPath("~/UploadedFiles/Swati-Sign.png");
iTextSharp.text.Image jpgSign = iTextSharp.text.Image.GetInstance(imageURL3);
////Resize image depend upon your need
jpgSign.ScaleToFit(140f, 120f);
jpgSign.SpacingBefore = 10f;
//////Give some space after the image
jpgSign.SpacingAfter = 1f;
jpgSign.Alignment = Element.ALIGN_LEFT;
jpgSign.SetAbsolutePosition(40, 160);
//jpg12.
pdfDoc.Add(jpgSign);
}
string imageURL2 = Server.MapPath("~/UploadedFiles/footer.jpg");
iTextSharp.text.Image jpgFooter = iTextSharp.text.Image.GetInstance(imageURL2);
////Resize image depend upon your need
jpgFooter.ScaleToFit(140f, 120f);
jpgFooter.SpacingBefore = 10f;
//////Give some space after the image
jpgFooter.SpacingAfter = 1f;
jpgFooter.Alignment = Element.ALIGN_LEFT;
jpgFooter.ScaleAbsoluteWidth(510);
jpgFooter.ScaleAbsoluteHeight(70);
jpgFooter.SetAbsolutePosition(40, 0);
//jpg12.
pdfDoc.Add(jpgFooter);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
string imageURL4 = Server.MapPath("~/UploadedFiles/Swati-Sign.png");
iTextSharp.text.Image jpgFooterSign = iTextSharp.text.Image.GetInstance(imageURL4);
////Resize image depend upon your need
jpgFooterSign.ScaleToFit(140f, 120f);
jpgFooterSign.SpacingBefore = 10f;
//////Give some space after the image
jpgFooterSign.SpacingAfter = 1f;
jpgFooterSign.Alignment = Element.ALIGN_LEFT;
if ((fc["hdnFormatType"] == "ManageService"))
{
jpgFooterSign.SetAbsolutePosition(20, 150);
}
else
{
jpgFooterSign.SetAbsolutePosition(20, 450);
}
writer.DirectContent.AddImage(jpgFooterSign, false);
pdfDoc.Close();
return File(stream.ToArray(), "application/pdf", CandName + "-" + empId + ".pdf");
}
}
Try this one:- set positions also what you want.
public void AddImage(int pageNumber)
{
if (pageNumber > 0)
{
string pdfTemplate =
#"D:\Input.pdf";
string newFile = #"D:\Output.pdf";
PdfReader pdfReader = new PdfReader(pdfTemplate);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(
newFile, FileMode.Create));
AcroFields pdfFormFields = pdfStamper.AcroFields;
string chartLoc = string.Empty;
chartLoc = #"C:\img.png";
iTextSharp.text.Image chartImg = iTextSharp.text.Image.GetInstance(chartLoc);
iTextSharp.text.pdf.PdfContentByte underContent;
iTextSharp.text.Rectangle rect;
try
{
Single X, Y; int pageCount = 0;
rect = pdfReader.GetPageSizeWithRotation(1);
if (chartImg.Width > rect.Width || chartImg.Height > rect.Height)
{
chartImg.ScaleToFit(rect.Width, rect.Height);
X = (rect.Width - chartImg.ScaledWidth) / 2;
Y = (rect.Height - chartImg.ScaledHeight) / 2;
}
else
{
X = (rect.Width - chartImg.Width) / 2;
Y = (rect.Height - chartImg.Height) / 2;
}
chartImg.SetAbsolutePosition(X, Y);
pageCount = pdfReader.NumberOfPages;
//Below to add image to all pages
//for (int i = 1; i < pageCount; i++)
//{
// underContent = pdfStamper.GetOverContent(i);//.GetUnderContent(i);
// underContent.AddImage(chartImg);
//}
if (pageCount >= pageNumber)
{
underContent = pdfStamper.GetOverContent(pageNumber);//.GetUnderContent(i);
underContent.AddImage(chartImg);
}
pdfStamper.Close();
pdfReader.Close();
}
catch (Exception ex)
{
throw ex;
}
}
}
I want to export some image from some PDF File, to do this I should to use a PdfSharp library.
I have find the code on the web to export image file from one PDF but if the image is codifing by DCTDecode I don't have any problems. If the image ise codifing by FlatDecode mode I'm not able to export this Image.
So this is the code:
static void Main(string[] args)
{
//estrapolare immagine da pdf
const string filename = "d://eresult.pdf";
PdfDocument document = PdfReader.Open(filename);
int imageCount = 0;
// Iterate pages
foreach (PdfPage page in document.Pages)
{
// Get resources dictionary
PdfDictionary resources = page.Elements.GetDictionary("/Resources");
if (resources != null)
{
// Get external objects dictionary
PdfDictionary xObjects = resources.Elements.GetDictionary("/XObject");
if (xObjects != null)
{
ICollection<PdfItem> items = xObjects.Elements.Values;
// Iterate references to external objects
foreach (PdfItem item in items)
{
PdfReference reference = item as PdfReference;
if (reference != null)
{
PdfDictionary xObject = reference.Value as PdfDictionary;
// Is external object an image?
if (xObject != null && xObject.Elements.GetString("/Subtype") == "/Image")
{
ExportImage(xObject, ref imageCount);
}
}
}
}
}
}
System.Diagnostics.Debug.Write(imageCount + " images exported.", "Export Images");
}
static void ExportImage(PdfDictionary image, ref int count)
{
string filter = image.Elements.GetName("/Filter");
switch (filter)
{
case "/DCTDecode":
ExportJpegImage(image, ref count);
break;
case "/FlateDecode":
ExportAsPngImage(image, ref count);
break;
}
}
static void ExportJpegImage(PdfDictionary image, ref int count)
{
// Fortunately JPEG has native support in PDF and exporting an image is just writing the stream to a file.
byte[] stream = image.Stream.Value;
FileStream fs = new FileStream(String.Format("Image{0}.jpeg", count++), FileMode.Create, FileAccess.Write);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(stream);
bw.Close();
}
static void ExportAsPngImage(PdfDictionary image, ref int count)
{
int width = image.Elements.GetInteger(PdfImage.Keys.Width);
int height = image.Elements.GetInteger(PdfImage.Keys.Height);
int bitsPerComponent = image.Elements.GetInteger(PdfImage.Keys.BitsPerComponent);
PdfSharp.Pdf.Filters.FlateDecode flate = new PdfSharp.Pdf.Filters.FlateDecode();
byte[] decodedBytes = flate.Decode(image.Stream.Value);
System.Drawing.Imaging.PixelFormat pixelFormat;
switch (bitsPerComponent)
{
case 1:
pixelFormat = PixelFormat.Format1bppIndexed;
break;
case 8:
pixelFormat = PixelFormat.Format8bppIndexed;
break;
case 24:
pixelFormat = PixelFormat.Format24bppRgb;
break;
default:
throw new Exception("Unknown pixel format " + bitsPerComponent);
}
Bitmap bmp = new Bitmap(width, height, pixelFormat);
var bmpData = bmp.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.WriteOnly, pixelFormat);
int length = (int)Math.Ceiling(width * bitsPerComponent / 8.0);
for (int i = 0; i < height; i++)
{
int offset = i * length;
int scanOffset = i * bmpData.Stride;
Marshal.Copy(decodedBytes, offset, new IntPtr(bmpData.Scan0.ToInt32() + scanOffset), length);
}
bmp.UnlockBits(bmpData);
using (FileStream fs = new FileStream(#"D:\\" + String.Format("Image{0}.png", count++), FileMode.Create, FileAccess.Write))
{
bmp.Save(fs, System.Drawing.Imaging.ImageFormat.Png);
}
// TODO: You can put the code here that converts vom PDF internal image format to a Windows bitmap
// and use GDI+ to save it in PNG format.
// It is the work of a day or two for the most important formats. Take a look at the file
// PdfSharp.Pdf.Advanced/PdfImage.cs to see how we create the PDF image formats.
// We don't need that feature at the moment and therefore will not implement it.
// If you write the code for exporting images I would be pleased to publish it in a future release
// of PDFsharp.
}
With this code I can see the Image in this strange mode:
But the image in the Pdf file is this:
As you can see, the color is too different
Image data and color palette are different objects in the PDF file. Images can have masks and these would be different objects, too.
When saving image data to a PNG file, you also may have to get the color palette and include the color data in the PNG file.
Maybe the code shown on the PDFsharp forum works better than your code:
http://forum.pdfsharp.net/viewtopic.php?p=6755#p6755
I am uploading multiple photos using MultipleFileUpload, if I will upload big size images, then in slider image is not fixed size not showing proper looks. Is there any code for while uploading time restricts the size of images of the gallery.
Below is my c# code:
protected void lnkbtn_Submit_Click(object sender, EventArgs e)
{
try
{
if (MultipleFileUpload.HasFiles)
{
int MaxGalleryId, ReturnValue;
ReturnValue = obj.fnCreateNewPhotoGallery(txtGalleryName.Text, txtGalleryDescrption.Text, DateTime.Now, out MaxGalleryId);
if (ReturnValue != 0)
{
string GalleryPath = System.Configuration.ConfigurationManager.AppSettings["GalleryPath"] + MaxGalleryId;
Directory.CreateDirectory(Server.MapPath(GalleryPath));
string ThumbnailPath = System.Configuration.ConfigurationManager.AppSettings["ThumbnailPath"] + MaxGalleryId;
Directory.CreateDirectory(Server.MapPath(ThumbnailPath));
StringBuilder UploadedFileNames = new StringBuilder();
foreach (HttpPostedFile uploadedFile in MultipleFileUpload.PostedFiles)
{
//Upload file
string FileName = HttpUtility.HtmlEncode(Path.GetFileName(uploadedFile.FileName));
string SaveAsImage = System.IO.Path.Combine(Server.MapPath(GalleryPath + "/"), FileName);
uploadedFile.SaveAs(SaveAsImage);
//Create thumbnail for uploaded file and save thumbnail on disk
Bitmap Thumbnail = CreateThumbnail(SaveAsImage, 200, 200);
string SaveAsThumbnail = System.IO.Path.Combine(Server.MapPath(ThumbnailPath + "/"), FileName);
Thumbnail.Save(SaveAsThumbnail);
}
HTMLHelper.jsAlertAndRedirect(this, "Gallery created successfully. ", "Album.aspx?GalleryId=" + MaxGalleryId);
}
}
}
catch
{
HTMLHelper.jsAlertAndRedirect(this, "Gallery is not created. Some exception occured ", "CreateAlbum.aspx");
}
}
Below is my Create Thumbnail method code :
public Bitmap CreateThumbnail(string ImagePath, int ThumbnailWidth, int ThumbnailHeight)
{
System.Drawing.Bitmap Thumbnail = null;
try
{
Bitmap ImageBMP = new Bitmap(ImagePath);
ImageFormat loFormat = ImageBMP.RawFormat;
decimal lengthRatio;
int ThumbnailNewWidth = 0;
int ThumbnailNewHeight = 0;
decimal ThumbnailRatioWidth;
decimal ThumbnailRatioHeight;
// If the uploaded image is smaller than a thumbnail size the just return it
if (ImageBMP.Width <= ThumbnailWidth && ImageBMP.Height <= ThumbnailHeight)
return ImageBMP;
// Compute best ratio to scale entire image based on larger dimension.
if (ImageBMP.Width > ImageBMP.Height)
{
ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
ThumbnailNewWidth = ThumbnailWidth;
decimal lengthTemp = ImageBMP.Height * lengthRatio;
ThumbnailNewHeight = (int)lengthTemp;
}
else
{
ThumbnailRatioWidth = (decimal)ThumbnailWidth / ImageBMP.Width;
ThumbnailRatioHeight = (decimal)ThumbnailHeight / ImageBMP.Height;
lengthRatio = Math.Min(ThumbnailRatioWidth, ThumbnailRatioHeight);
ThumbnailNewHeight = ThumbnailHeight;
decimal lengthTemp = ImageBMP.Width * lengthRatio;
ThumbnailNewWidth = (int)lengthTemp;
}
Thumbnail = new Bitmap(ThumbnailNewWidth, ThumbnailNewHeight);
Graphics g = Graphics.FromImage(Thumbnail);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);
g.DrawImage(ImageBMP, 0, 0, ThumbnailNewWidth, ThumbnailNewHeight);
ImageBMP.Dispose();
}
catch
{
return null;
}
return Thumbnail;
}
The above code there is a command line //Upload file from there uploading images. I used this example for the gallery:
http://www.bugdebugzone.com/2013/10/create-dynamic-image-gallery-slideshow.html
You can the ContentLength property of uploadedFile as such:
if (uploadedFile.ContentLength > 1000000)
{
continue;
}
ContentLength is the size in bytes of the uploaded file.
https://msdn.microsoft.com/en-us/library/system.web.httppostedfile.contentlength(v=vs.110).aspx