I want to watermark files in a folder with another image. However, am getting the error
'Parameter Not Valid'
when invoking the code
img.Save(filepath, System.Drawing.Imaging.ImageFormat.Jpeg);
I have the following code;
public static string WatermarkImagesInFolder(string url)
{
if (url == null)
throw new Exception("URL must be provided");
string path = HttpContext.Current.Server.MapPath(url);
if (!Directory.Exists(path))
throw new DirectoryNotFoundException();
Directory.CreateDirectory(String.Format(#"{0}\watermarked", path));
List<string> urls = GetJpgFilesFromFolder(path);
foreach (string imageUrl in urls)
{
Image img = WatermarkImage(imageUrl);
string filename = Path.GetFileName(imageUrl);
string filepath = String.Format(#"{0}\watermarked\{1}", path, filename);
img.Save(filepath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
return "complete";
}
and
public static Image WatermarkImage(string filename)
{
using (Image image = Image.FromFile(filename))
using (Image watermarkImage = Image.FromFile(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["WatermarkImageUrl"])))
using (Graphics imageGraphics = Graphics.FromImage(image))
using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))
{
int x = (image.Width / 2 - watermarkImage.Width / 2);
int y = (image.Height / 2 - watermarkImage.Height / 2);
watermarkBrush.TranslateTransform(x, y);
imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width + 1, watermarkImage.Height)));
return image;
}
}
as an example of input for img.save;
img.save("C:\\IMAGES\\wateremarked\\IMAGE (1).jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
any ideas on what could be causing the error here please?
In your WatermarkImage you have the image object in a using statement. As soon as that goes out of scope, Dispose is invoked on the image. You would need to return a copy of the image - or not use the using statement & ensure you dispose properly later.
See : Exception: Parameter is not valid (on passing new image to pictureBox)
public static string WatermarkImagesInFolder(string url)
{
if (url == null)
throw new Exception("URL must be provided");
string path = HttpContext.Current.Server.MapPath(url);
if (!Directory.Exists(path))
throw new DirectoryNotFoundException();
Directory.CreateDirectory(String.Format(#"{0}\watermarked", path));
List<string> urls = GetJpgFilesFromFolder(path);
foreach (string imageUrl in urls)
{
using(Image img = WatermarkImage(imageUrl))
{
string filename = Path.GetFileName(imageUrl);
string filepath = String.Format(#"{0}\watermarked\{1}", path, filename);
img.Save(filepath, System.Drawing.Imaging.ImageFormat.Jpeg);
}
}
return "complete";
}
public static Image WatermarkImage(string filename)
{
Image image = Image.FromFile(filename);
using (Image watermarkImage = Image.FromFile(HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["WatermarkImageUrl"])))
using (Graphics imageGraphics = Graphics.FromImage(image))
using (TextureBrush watermarkBrush = new TextureBrush(watermarkImage))
{
int x = (image.Width / 2 - watermarkImage.Width / 2);
int y = (image.Height / 2 - watermarkImage.Height / 2);
watermarkBrush.TranslateTransform(x, y);
imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(x, y), new Size(watermarkImage.Width + 1, watermarkImage.Height)));
return image;
}
}
Here is my alternative solution, which gives the ability to use picture stream, but not it's location as it's currently browsed from Kendo Control as in my example and it still have not physical location yet.
public static Image ApplyWatermark(HttpPostedFileBase img, string appDataPath)
{
Image resultImage = null;
using (Image image = Image.FromStream(img.InputStream))
{
using (Image watermarkImage = Image.FromFile(appDataPath + "\\Watermark\\sample-watermark.png"))
{
using (Graphics imageGraphics = Graphics.FromImage(image))
{
using (Brush watermarkBrush = new TextureBrush(watermarkImage))
{
imageGraphics.FillRectangle(watermarkBrush, new Rectangle(new Point(0, 0), image.Size));
resultImage = (Image)image.Clone();
}
}
}
}
return resultImage;
}
private void SaveImagesOnDisk(IEnumerable<HttpPostedFileBase> images, int rentalPropertyId)
{
if (images != null)
{
foreach (var file in images)
{
// Some browsers send file names with full path. This needs to be stripped.
var fileName = Path.GetFileName(file.FileName);
var appDataPath = this.Server.MapPath("~/App_Data/");
var newPath = Path.Combine(appDataPath, rentalPropertyId.ToString());
if (!Directory.Exists(newPath))
{
DirectoryInfo di = Directory.CreateDirectory(newPath);
}
var physicalPath = Path.Combine(newPath, fileName);
System.Drawing.Image markedImage = Helper.ApplyWatermark(file, appDataPath);
markedImage.Save(physicalPath, System.Drawing.Imaging.ImageFormat.Png);
}
}
//return this.Json(new { status = "OK" }, "text/plain");
}
Related
I have a file upload control that allows users to upload an image file. Rather then forcing them to use a specific size image, I am trying to resize it, save it the resized version to a folder and then delete the original.
When I try to delete the file, I keep getting "file in use" exception. I have searched and tried all suggestions to no avail.
This is the latest try, at which point I decided to seek help. I pass the source path (where original file is in, a destination path where resized file is to end up in, file name and width to which it should be resized, keeping aspect ratio):
public static void CreateResizedCopy(String sourcePath, String destinationPath, String filename, int width)
{
if (!File.Exists(destinationPath + filename))
{
System.Drawing.Image image = System.Drawing.Image.FromFile(sourcePath + filename);
float AspectRatio = (float)image.Size.Width / (float)image.Size.Height;
int newHeight = Convert.ToInt32(width / AspectRatio);
Bitmap thumbnailBitmap = new Bitmap(width, newHeight);
Graphics thumbnailGraph = Graphics.FromImage(thumbnailBitmap);
thumbnailGraph.CompositingQuality = CompositingQuality.HighQuality;
thumbnailGraph.SmoothingMode = SmoothingMode.HighQuality;
thumbnailGraph.InterpolationMode = InterpolationMode.HighQualityBicubic;
var imageRectangle = new Rectangle(0, 0, width, newHeight);
thumbnailGraph.DrawImage(image, imageRectangle);
thumbnailBitmap.Save(destinationPath + filename, ImageFormat.Jpeg);
thumbnailGraph.Dispose();
thumbnailBitmap.Dispose();
image.Dispose();
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
if (!FileInUse(sourcePath + filename))
{
File.Delete(sourcePath + filename);
}
else
{
// Error here: file is in use
using (FileStream fs = new FileStream(sourcePath + filename, FileMode.OpenOrCreate))
fs.Dispose();
}
}
}
public static bool FileInUse(string path)
{
try
{
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
return false;
}
}
catch (IOException ex)
{
return true;
}
}
UPDATE
This is the AJAX AsynFileUpload's upload completed event handler. It saves the file to a "Resize" folder. If image needs to be resized, it calls the method to resize it and then moves it to its final resting place. If not, no resizing is done, it just moves the file. It then "attempts" to delete the file in resize folder and it chokes!
protected void fuNewsImage_UploadedComplete_Resize(object sender, AsyncFileUploadEventArgs e)
{
if (fuNewsImage.HasFile)
{
HttpPostedFile file = fuNewsImage.PostedFile;
string sFileName = fuNewsImage.FileName;
string sFileSize = e.FileSize;
string sSaveFolder = ImageFilePath.TEMP_FOLDER_EA_TEST + "\\";
string sResizeFolder = ImageFilePath.TEMP_FOLDER_EA_TEST + "\\Resized\\";
fuNewsImage.SaveAs(Server.MapPath(sResizeFolder + sFileName));
System.Drawing.Image img = System.Drawing.Image.FromFile(Server.MapPath(sResizeFolder) + sFileName);
int iImgWidth = img.Width;
int iImgHeight = img.Height;
if (iImgWidth > ImageInfo.MAX_WIDTH)
{
// sSaveFolder is the efinal resting place of the uploaded image
// If image width is more than max allowed, resize it, save it in sSaveFolder
Utils.CreateResizedCopy(Server.MapPath(sResizeFolder), Server.MapPath(sSaveFolder), sFileName, 600);
System.Threading.Thread.Sleep(1000);
File.Delete(Server.MapPath(sSaveFolder + sFileName));
}
else // just move it t sSaveFolder
{
File.Move(Server.MapPath(sResizeFolder) + sFileName, Server.MapPath(sSaveFolder) + sFileName);
}
// --- Chokes here ---
Array.ForEach(Directory.GetFiles(Server.MapPath(sResizeFolder)), File.Delete);
}
}
I have problem with my code, I've tryed string originalImage = null;.
But this not really working. Because its not taking original file name somehow..
Code:
private void textBox1_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.RootFolder = Environment.SpecialFolder.Desktop;
fbd.Description = "+++ Select path +++";
fbd.ShowNewFolderButton = false;
if (fbd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fbd.SelectedPath;
}
string[] originalImage = Directory.GetFiles(textBox1.Text, "*.JPG");
foreach (var filename in originalImage)
{
Bitmap bitmap = new Bitmap(filename);
//DefaultCompressionJpeg(bitmap);
VariousQuality(bitmap);
}
}
string originalImage = null;
public void VariousQuality(Image original)
{
ImageCodecInfo jpgEncoder = null;
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == ImageFormat.Jpeg.Guid)
{
jpgEncoder = codec;
break;
}
}
if (jpgEncoder != null)
{
Encoder encoder = Encoder.Quality;
EncoderParameters encoderParameters = new EncoderParameters(1);
for (long quality = 90; quality <= 90;)
{
EncoderParameter encoderParameter = new EncoderParameter(encoder, quality);
encoderParameters.Param[0] = encoderParameter;
string fileOut = Path.Combine(#"C:\Users\Kristen\Desktop\pilt2", originalImage + ".jpeg");
Debug.WriteLine(fileOut);
FileStream ms = new FileStream(fileOut, FileMode.Create, FileAccess.Write);
original.Save(ms, jpgEncoder, encoderParameters);
ms.Flush();
ms.Close();
}
}
}
Kind regards,
In you click eventhandler you have a local variable string [] originalImage which you initialize with all the filenames in some directory.
On class level you have a field string originalImage which you initialize with null.
These two elements do have nothing to do with each other, they are completely unrelated.
So in your compression method you use an originalImage to construct a filename. The only entity of this name known in this method is the string field of the class, which has a null value.
You should add a second parameter to your compression method where you pass the current filename to your method and remove the field from the class.
public void VariousQuality (Bitmap original, string filename) {
...
string fileOut = Path.Combine(#"C:\Users\Kristen\Desktop\pilt2", filename + ".jpeg");
}
Call the method as follows
foreach (var filename in originalImage) {
Bitmap bitmap = new Bitmap(filename);
//DefaultCompressionJpeg(bitmap);
string fn = Path.GetFileNameWithoutExtension(filename);
VariousQuality(bitmap, fn);
}
As someone suggested in the comments (which they mysteriously deleted because they were definitely on to something), it seems like you're trying to refer to the original argument:
public void VariousQuality(Image original)
Just rename either that arg to originalImage or rename the other in your code to original.
I want to capture only some part of desktop screen. for example I've opened 4,5 different window explorer, browsers, some MS office files and other stuff. and I want to take screenshot which only include some of them(windows). Not All windows.
string appPath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory) + #"\screenshots\";
string imgName = name + DateTime.Now.Ticks + #".JPEG";
Bitmap memoryImage = null;
Graphics memoryGraphics = null;
int width = Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenWidth);
int height = Convert.ToInt32(System.Windows.SystemParameters.PrimaryScreenHeight);
System.Drawing.Size s = new System.Drawing.Size(width, height);
string str = "";
try
{
str = appPath + imgName;
}
catch (Exception er)
{
MessageBox.Show(er.Message.ToString());
}
using (memoryImage = new Bitmap(width, height))
{
using (memoryGraphics = Graphics.FromImage(memoryImage))
{
memoryGraphics.CopyFromScreen(0, 0, 0, 0, s);
memoryImage.Save(str);
}
}
memoryImage.Dispose();
memoryGraphics.Dispose();
I'm using above code, which simple give me screenshot of my desktop.
I'm implementing "copy map to clip" as an image.
what I do is I create an image an save it to certain directory and copy it to clipboard.
but before I do that I delete every file that exist in the directory, but now I cant since, the image is being used by clipboard.
here's my code.
public override void OnClick()
{
//base.OnClick();
DeleteOldCopiedJPG();
System.Windows.Forms.Clipboard.Clear();
string fileName = System.Windows.Forms.Application.ExecutablePath.Substring(0, System.Windows.Forms.Application.ExecutablePath.LastIndexOf("\\") + 1) + Guid.NewGuid() + ".jpg";
//System.Windows.Forms.Cursor.Current = Cursors.Wait;
//if (System.IO.File.Exists(fileName))
// System.IO.File.Delete(fileName);
IExport objExport = (IExport)new ExportJPEG();
objExport.ExportFileName = fileName;
#if Debug || Release
ESRI.ArcGIS.Display.tagRECT objExportRECT = default( ESRI.ArcGIS.Display.tagRECT);
#else
tagRECT objExportRECT = default(tagRECT);
#endif
var _with1 = objExportRECT;
_with1.left = mapControl.ActiveView.ExportFrame.left;
_with1.top = mapControl.ActiveView.ExportFrame.top;
_with1.right = mapControl.ActiveView.ExportFrame.right;
_with1.bottom = mapControl.ActiveView.ExportFrame.bottom;
IEnvelope envelope = new EnvelopeClass();
envelope.PutCoords(mapControl.ActiveView.ExportFrame.left, mapControl.ActiveView.ExportFrame.top,
mapControl.ActiveView.ExportFrame.right, mapControl.ActiveView.ExportFrame.bottom);
objExport.PixelBounds = envelope;
System.Int32 intHDC = objExport.StartExporting();
mapControl.ActiveView.Output(intHDC, Convert.ToInt16(objExport.Resolution), objExportRECT, null, null);
objExport.FinishExporting();
objExport.Cleanup();
System.Drawing.Image objImage = System.Drawing.Bitmap.FromFile(fileName);
System.Windows.Forms.Clipboard.SetImage(objImage);
//RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap(200, 200, 96, 96, PixelFormats.Pbgra32);
//renderTargetBitmap.Render((Visual)mapControl.ActiveView.ScreenDisplay);
//Clipboard.SetImage(renderTargetBitmap);
}
private void DeleteOldCopiedJPG(string Path)
{
string[] filePaths = Directory.GetFiles(System.Windows.Forms.Application.ExecutablePath.Substring(0, System.Windows.Forms.Application.ExecutablePath.LastIndexOf("\\") + 1));
foreach (string filepath in filePaths)
if (filepath.Substring(filepath.Length - 4) == ".jpg")
try{ File.Delete(filepath); } catch {}
}
You need to dispose the image after inserting it into the clipboard:
using (System.Drawing.Image objImage = System.Drawing.Bitmap.FromFile(fileName))
{
System.Windows.Forms.Clipboard.SetImage(objImage);
}
Otherwise it will remain open until the garbage collector calls the finalizer for objImage.
I am trying to extract all the images from a pdf using itextsharp but can't seem to overcome this one hurdle.
The error occures on the line System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS); giving an error of "Parameter is not valid".
I think it works when the image is a bitmap but not of any other format.
I have this following code - sorry for the length;
private void Form1_Load(object sender, EventArgs e)
{
FileStream fs = File.OpenRead(#"reader.pdf");
byte[] data = new byte[fs.Length];
fs.Read(data, 0, (int)fs.Length);
List<System.Drawing.Image> ImgList = new List<System.Drawing.Image>();
iTextSharp.text.pdf.RandomAccessFileOrArray RAFObj = null;
iTextSharp.text.pdf.PdfReader PDFReaderObj = null;
iTextSharp.text.pdf.PdfObject PDFObj = null;
iTextSharp.text.pdf.PdfStream PDFStremObj = null;
try
{
RAFObj = new iTextSharp.text.pdf.RandomAccessFileOrArray(data);
PDFReaderObj = new iTextSharp.text.pdf.PdfReader(RAFObj, null);
for (int i = 0; i <= PDFReaderObj.XrefSize - 1; i++)
{
PDFObj = PDFReaderObj.GetPdfObject(i);
if ((PDFObj != null) && PDFObj.IsStream())
{
PDFStremObj = (iTextSharp.text.pdf.PdfStream)PDFObj;
iTextSharp.text.pdf.PdfObject subtype = PDFStremObj.Get(iTextSharp.text.pdf.PdfName.SUBTYPE);
if ((subtype != null) && subtype.ToString() == iTextSharp.text.pdf.PdfName.IMAGE.ToString())
{
byte[] bytes = iTextSharp.text.pdf.PdfReader.GetStreamBytesRaw((iTextSharp.text.pdf.PRStream)PDFStremObj);
if ((bytes != null))
{
try
{
System.IO.MemoryStream MS = new System.IO.MemoryStream(bytes);
MS.Position = 0;
System.Drawing.Image ImgPDF = System.Drawing.Image.FromStream(MS);
ImgList.Add(ImgPDF);
}
catch (Exception)
{
}
}
}
}
}
PDFReaderObj.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
} //Form1_Load
Resolved...
Even I got the same exception of "Parameter is not valid" and after so much of
work with the help of the link provided by der_chirurg
(http://kuujinbo.info/iTextSharp/CCITTFaxDecodeExtract.aspx ) I resolved it
and following is the code:
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using iTextSharp.text.pdf.parser;
using Dotnet = System.Drawing.Image;
using iTextSharp.text.pdf;
namespace PDF_Parsing
{
partial class PDF_ImgExtraction
{
string imgPath;
private void ExtractImage(string pdfFile)
{
PdfReader pdfReader = new PdfReader(files[fileIndex]);
for (int pageNumber = 1; pageNumber <= pdfReader.NumberOfPages; pageNumber++)
{
PdfReader pdf = new PdfReader(pdfFile);
PdfDictionary pg = pdf.GetPageN(pageNumber);
PdfDictionary res = (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
PdfDictionary xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
foreach (PdfName name in xobj.Keys)
{
PdfObject obj = xobj.Get(name);
if (obj.IsIndirect())
{
PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
string width = tg.Get(PdfName.WIDTH).ToString();
string height = tg.Get(PdfName.HEIGHT).ToString();
ImageRenderInfo imgRI = ImageRenderInfo.CreateForXObject(new Matrix(float.Parse(width), float.Parse(height)), (PRIndirectReference)obj, tg);
RenderImage(imgRI);
}
}
}
}
private void RenderImage(ImageRenderInfo renderInfo)
{
PdfImageObject image = renderInfo.GetImage();
using (Dotnet dotnetImg = image.GetDrawingImage())
{
if (dotnetImg != null)
{
using (MemoryStream ms = new MemoryStream())
{
dotnetImg.Save(ms, ImageFormat.Tiff);
Bitmap d = new Bitmap(dotnetImg);
d.Save(imgPath);
}
}
}
}
}
}
You need to check the stream's /Filter to see what image format a given image uses. It may be a standard image format:
DCTDecode (jpeg)
JPXDecode (jpeg 2000)
JBIG2Decode (jbig is a B&W only format)
CCITTFaxDecode (fax format, PDF supports group 3 and 4)
Other than that, you'll need to get the raw bytes (as you are), and build an image using the image stream's width, height, bits per component, number of color components (could be CMYK, indexed, RGB, or Something Weird), and a few others, as defined in section 8.9 of the ISO PDF SPECIFICATION (available for free).
So in some cases your code will work, but in others, it'll fail with the exception you mentioned.
PS: When you have an exception, PLEASE include the stack trace every single time. Pretty please with sugar on top?
Works for me like this, using these two methods:
public static List<System.Drawing.Image> ExtractImagesFromPDF(byte[] bytes)
{
var imgs = new List<System.Drawing.Image>();
var pdf = new PdfReader(bytes);
try
{
for (int pageNumber = 1; pageNumber <= pdf.NumberOfPages; pageNumber++)
{
PdfDictionary pg = pdf.GetPageN(pageNumber);
List<PdfObject> objs = FindImageInPDFDictionary(pg);
foreach (var obj in objs)
{
if (obj != null)
{
int XrefIndex = Convert.ToInt32(((PRIndirectReference)obj).Number.ToString(System.Globalization.CultureInfo.InvariantCulture));
PdfObject pdfObj = pdf.GetPdfObject(XrefIndex);
PdfStream pdfStrem = (PdfStream)pdfObj;
var pdfImage = new PdfImageObject((PRStream)pdfStrem);
var img = pdfImage.GetDrawingImage();
imgs.Add(img);
}
}
}
}
finally
{
pdf.Close();
}
return imgs;
}
private static List<PdfObject> FindImageInPDFDictionary(PdfDictionary pg)
{
var res = (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));
var xobj = (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
var pdfObgs = new List<PdfObject>();
if (xobj != null)
{
foreach (PdfName name in xobj.Keys)
{
PdfObject obj = xobj.Get(name);
if (obj.IsIndirect())
{
var tg = (PdfDictionary)PdfReader.GetPdfObject(obj);
var type = (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));
if (PdfName.IMAGE.Equals(type)) // image at the root of the pdf
{
pdfObgs.Add(obj);
}
else if (PdfName.FORM.Equals(type)) // image inside a form
{
FindImageInPDFDictionary(tg).ForEach(o => pdfObgs.Add(o));
}
else if (PdfName.GROUP.Equals(type)) // image inside a group
{
FindImageInPDFDictionary(tg).ForEach(o => pdfObgs.Add(o));
}
}
}
}
return pdfObgs;
}
In newer version of iTextSharp, the 1st parameter of ImageRenderInfo.CreateForXObject is not Matrix anymore but GraphicsState. #der_chirurg's approach should work. I tested myself with the information from the following link and it worked beautifully:
http://www.thevalvepage.com/swmonkey/2014/11/26/extract-images-from-pdf-files-using-itextsharp/
To extract all Images on all Pages, it is not necessary to implement different filters. iTextSharp has an Image Renderer, which saves all Images in their original image type.
Just do the following found here: http://kuujinbo.info/iTextSharp/CCITTFaxDecodeExtract.aspx You don't need to implement HttpHandler...
I added library on github which, extract images in PDF and compress them.
Could be useful, when you are going to start play with very powerful library ITextSharp.
Here the link: https://github.com/rock-walker/PdfCompression
This works for me and I think it's a simple solution:
Write a custom RenderListener and implement its RenderImage method, something like this
public void RenderImage(ImageRenderInfo info)
{
PdfImageObject image = info.GetImage();
Parser.Matrix matrix = info.GetImageCTM();
var fileType = image.GetFileType();
ImageFormat format;
switch (fileType)
{//you may add more types here
case "jpg":
case "jpeg":
format = ImageFormat.Jpeg;
break;
case "pnt":
format = ImageFormat.Png;
break;
case "bmp":
format = ImageFormat.Bmp;
break;
case "tiff":
format = ImageFormat.Tiff;
break;
case "gif":
format = ImageFormat.Gif;
break;
default:
format = ImageFormat.Jpeg;
break;
}
var pic = image.GetDrawingImage();
var x = matrix[Parser.Matrix.I31];
var y = matrix[Parser.Matrix.I32];
var width = matrix[Parser.Matrix.I11];
var height = matrix[Parser.Matrix.I22];
if (x < <some value> && y < <some value>)
{
return;//ignore these images
}
pic.Save(<path and name>, format);
}
I have used this library in the past without any problems.
http://www.winnovative-software.com/PdfImgExtractor.aspx
private void btnExtractImages_Click(object sender, EventArgs e)
{
if (pdfFileTextBox.Text.Trim().Equals(String.Empty))
{
MessageBox.Show("Please choose a source PDF file", "Choose PDF file", MessageBoxButtons.OK);
return;
}
// the source pdf file
string pdfFileName = pdfFileTextBox.Text.Trim();
// start page number
int startPageNumber = int.Parse(textBoxStartPage.Text.Trim());
// end page number
// when it is 0 the extraction will continue up to the end of document
int endPageNumber = 0;
if (textBoxEndPage.Text.Trim() != String.Empty)
endPageNumber = int.Parse(textBoxEndPage.Text.Trim());
// create the PDF images extractor object
PdfImagesExtractor pdfImagesExtractor = new PdfImagesExtractor();
pdfImagesExtractor.LicenseKey = "31FAUEJHUEBQRl5AUENBXkFCXklJSUlQQA==";
// the demo output directory
string outputDirectory = Path.Combine(Application.StartupPath, #"DemoFiles\Output");
Cursor = Cursors.WaitCursor;
// set the handler to be called when an image was extracted
pdfImagesExtractor.ImageExtractedEvent += pdfImagesExtractor_ImageExtractedEvent;
try
{
// start images counting
imageIndex = 0;
// call the images extractor to raise the ImageExtractedEvent event when an images is extracted from a PDF page
// the pdfImagesExtractor_ImageExtractedEvent handler below will be executed for each extracted image
pdfImagesExtractor.ExtractImagesInEvent(pdfFileName, startPageNumber, endPageNumber);
// Alternatively you can use the ExtractImages() and ExtractImagesToFile() methods
// to extracted the images from a PDF document in memory or to image files in a directory
// uncomment the line below to extract the images to an array of ExtractedImage objects
//ExtractedImage[] pdfPageImages = pdfImagesExtractor.ExtractImages(pdfFileName, startPageNumber, endPageNumber);
// uncomment the lines below to extract the images to image files in a directory
//string outputDirectory = System.IO.Path.Combine(Application.StartupPath, #"DemoFiles\Output");
//pdfImagesExtractor.ExtractImagesToFile(pdfFileName, startPageNumber, endPageNumber, outputDirectory, "pdfimage");
}
catch (Exception ex)
{
// The extraction failed
MessageBox.Show(String.Format("An error occurred. {0}", ex.Message), "Error");
return;
}
finally
{
// uninstall the event handler
pdfImagesExtractor.ImageExtractedEvent -= pdfImagesExtractor_ImageExtractedEvent;
Cursor = Cursors.Arrow;
}
try
{
System.Diagnostics.Process.Start(outputDirectory);
}
catch (Exception ex)
{
MessageBox.Show(string.Format("Cannot open output folder. {0}", ex.Message));
return;
}
}
/// <summary>
/// The ImageExtractedEvent event handler called after an image was extracted from a PDF page.
/// The event is raised when the ExtractImagesInEvent() method is used
/// </summary>
/// <param name="args">The handler argument containing the extracted image and the PDF page number</param>
void pdfImagesExtractor_ImageExtractedEvent(ImageExtractedEventArgs args)
{
// get the image object and page number from even handler argument
Image pdfPageImageObj = args.ExtractedImage.ImageObject;
int pageNumber = args.ExtractedImage.PageNumber;
// save the extracted image to a PNG file
string outputPageImage = Path.Combine(Application.StartupPath, #"DemoFiles\Output",
"pdfimage_" + pageNumber.ToString() + "_" + imageIndex++ + ".png");
pdfPageImageObj.Save(outputPageImage, ImageFormat.Png);
args.ExtractedImage.Dispose();
}