How to delete image after save using Bitmap object with Selenium c#? - c#

I am using selenium C# to take screenshots. Convert as Bitmap and then Save to specific path. After save complete. I want to delete that same screenshot. It doesn't allow me to delete and throw the file that is being used by another process.
Below is my code:
public Bitmap GetScreenshot(IWebDriver driver)
{
//Take Screenshot
Screenshot screenshot = (driver as ITakesScreenshot).GetScreenshot();
//Convert Screenshot to Bitmap
var img = Image.FromStream(new MemoryStream(screenshot.AsByteArray)) as Bitmap;
return img;
}
I used above function like this:
var img = GetScreenshot(driver);
seleniumExtras.SaveImageAsPDF(img, "fullpage.jpeg");
Here is the function SaveImageAsPDF:
public void SaveImageAsPDF(Bitmap imageData, string ImagePath)
{
imageData.Save(ImagePath, ImageFormat.Jpeg);
imageData.Dispose();
//Save as PDF
System.Drawing.Image image = System.Drawing.Image.FromFile(ImagePath);
iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4);
doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
iTextSharp.text.pdf.PdfWriter.GetInstance(doc, new FileStream(ImagePath.Replace(".jpeg", ".pdf"), FileMode.Create));
doc.Open();
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
//pdfImage.SetAbsolutePosition(0, 0); // set the position to bottom left corner of pdf
pdfImage.ScaleAbsolute(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height); // set the height and width of image to PDF page size
pdfImage.ScaleToFit(iTextSharp.text.PageSize.A4.Width, iTextSharp.text.PageSize.A4.Height);
doc.Add(pdfImage);
doc.Close();
doc.Dispose();
//Delete image file after PDF created
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
//imageData.Dispose();
imageData.Dispose();
if (File.Exists(ImagePath))
File.Delete(ImagePath);
}

Related

how to display image in picturebox without saving in local file system in C#?

//Retrieve an image in Jpg format and store it into a variable.
var imgFile = (ImageFile)ScanerItem.Transfer(FormatID.wiaFormatJPEG);
var Path = #"D:\ScanImg.jpg";
// save the image in some path with filename.
imgFile.SaveFile(Path);
pictureBox1.ImageLocation = Path;
Based on the following SO answer, you can get the byte[] of the image with (byte[])imgFile.FileData.get_BinaryData():
converting .__comobj WIA to byte[] in C# application
A bitmap can be put as source into the PictureBox.
Therefore the byte[] as to put into a MemoryStream and create a Bitmap:
var imgFile = (ImageFile)ScanerItem.Transfer(FormatID.wiaFormatJPEG);
byte[] imageBytes = (byte[])imgFile.FileData.get_BinaryData();
Bitmap image;
using (MemoryStream stream = new MemoryStream(imageBytes))
{
image = new Bitmap(stream);
}
pictureBox1.Image = image;

Print the panel's content to a PDF

I create a form:
The "button1" add new content to my panel and there is a scrollbar:
I want to save the content of my panel to a PDF. It's not very hard:
Bitmap MemoryImage;
using (SaveFileDialog sfd = new SaveFileDialog() { Filter = "PDF file|*.pdf", ValidateNames = true })
{
if (sfd.ShowDialog() == DialogResult.OK)
{
iTextSharp.text.Document doc = new iTextSharp.text.Document(PageSize.A4.Rotate());
try
{
panelTombi.AutoSize = true;
panelTombi.Refresh();
int width = panelTombi.Width;
int height = panelTombi.Height;
MemoryImage = new Bitmap(width, height);
System.Drawing.Rectangle rect = new System.Drawing.Rectangle(0, 0, width, height);
panelTombi.DrawToBitmap(MemoryImage, new System.Drawing.Rectangle(0, 0, width, height));
iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance((System.Drawing.Image)MemoryImage, System.Drawing.Imaging.ImageFormat.Png);
image1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
MemoryImage.Save("ttt.png"); // Pour voir l'image qui devrait être ajoutée dans le PDF
//Save pdf file
PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
doc.Open();
doc.Add(image1);
panelTombi.AutoSize = false;
panelTombi.Refresh();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
finally
{
doc.Close();
}
}
}
I save the content to a Bitmap, I create a PDF instance, I add the image to the PDF, I close the PDF.
In order to test that, I save the Bitmap to an image and it works:
but there is a problem in the PDF ...
The image seems to have a big zoom, the left part is missing as well as the bottom of the image.
Would you know where the error lies please?
I prefer to have a PDF to save on my computer because it is much easier to see the number of pages needed.
thank you in advance
Add this code only and create perfect pdf
image1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
image1.ScaleToFit(PageSize.A4.Rotate().Width - 50f, PageSize.A4.Rotate().Height - 50f);

Tiff Image :How to set metadata for the mulltipage tiff programatically in .Net?

I am trying to set metadata for multi-page tiff image. Below is code snippet setting metadata for single-page tiff image.
Bitmap imageSource = img as Bitmap; // img is an original singlepage tiff image
Bitmap tempBitmap = new Bitmap(imageSource.Width, imageSource.Height);
try
{
ImageCodecInfo encoderInfo = GetEncoderInfo("image/tiff");
EncoderParameters encoderParams = new EncoderParameters(2);
EncoderParameter parameter = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)EncoderValue.CompressionCCITT3);
encoderParams.Param[0] = parameter;
parameter = new EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag,(long)EncoderValue.Flush);
encoderParams.Param[1] = parameter;
//Set the resolution as of the image file
tempBitmap.SetResolution(imageSource.HorizontalResolution, imageSource.VerticalResolution);
using (Graphics graphics = Graphics.FromImage(tempBitmap))
{
//Draw the image in the Empty bitmap by passing original imageSource
graphics.DrawImage(imageSource, 0, 0, (float)imageSource.Width, (float)imageSource.Height);
}
string strSign = "I am author";
PropertyItem propItem = img.PropertyItems[0];
propItem.Id = 315; // this is called 'Author'
propItem.Type = 2;
propItem.Value = System.Text.Encoding.UTF8.GetBytes(strSign + "\0");//signature;
propItem.Len = propItem.Value.Length;
((Image)tempBitmap).SetPropertyItem(propItem);
img.Dispose();
((Image)tempBitmap).Save("sample.tif", encoderInfo, encoderParams);
}
catch (Exception ex)
{
}
This above code works fine for single-page image, but cant achieve setting metadata for multi-page image. I am bit new to this, any useful links or libraries available to achieve setting matadata for multi-page tiff image would be helpful.

How to insert a dynamically generated bitmap into PDF document using PDFsharp?

I am trying to use PDFsharp to insert a dynamically generated bitmap of a QR Code in to a PDF document. I don't want to save the bitmap to the file but just want to insert it into the PDF. The problem I'm having is the DrawImage command is looking for a string where the image file is located. But I don't want to save the file, I just want to insert it into the PDF document. Is there a way of doing this?
var QRCode_BMP = _generalCode.QR_CodeGenerator(AddReviewPath); //This generates the bitmap
MemoryStream streamQR = new MemoryStream();
QRCode_BMP.Save(streamQR, System.Drawing.Imaging.ImageFormat.Jpeg); //save bitmap into memory stream in jpeg format System.Drawing.Image QR_Jpeg = System.Drawing.Image.FromStream(streamQR);// save memory stream to image file
XImage xImage = XImage.FromGdiPlusImage(QR_Jpeg);
gfx = XGraphics.FromPdfPage(page);
DrawImage(gfx, xImage, 0, 0, 100, 100); //This is not working
QRCode_BMP.Dispose();
streamQR.Close();
gfx.Dispose();
You create a QR code in QRCode_BMP and then you create an XImage from QR_Jpeg and write it is not working.
QRCode_BMP is only used to create a stream that is never used. We don't see where QR_Jpeg is coming from.
Provide a complete sample.
BTW: You can use XImage.FromStream to use the stream you created.
P.S.: IMHO JPEG is a bad choice for QR codes. Just use BMP and PDFsharp will use a lossless compression.
This is how I made it work;
PdfDocument pdf = PdfGenerator.GeneratePdf("<b>some html here</b>", PageSize.A4);
QRCodeGenerator qrGenerator = new QRCodeGenerator();
QRCodeData qrCodeData = qrGenerator.CreateQrCode("some text here", QRCodeGenerator.ECCLevel.Q);
QRCode qrCode = new QRCode(qrCodeData);
Bitmap qrCodeImage = qrCode.GetGraphic(10);
PdfPage page = pdf.Pages[0]; //I will add it to 1st page
// Get an XGraphics object for drawing
XGraphics gfx = XGraphics.FromPdfPage(page);
XImage image = XImage.FromGdiPlusImage(qrCodeImage); //you can use XImage.FromGdiPlusImage to get the bitmap object as image (not a stream)
gfx.DrawImage(image, 50, 50, 150, 150);
//save your pdf, dispose other objects
Using XImage.FromStream like #I liked the old Stack Overflow mentioned, in your posted code you should be able to just use:
var QRCode_BMP = _generalCode.QR_CodeGenerator(AddReviewPath); //This generates the bitmap
MemoryStream streamQR = new MemoryStream();
QRCode_BMP.Save(streamQR, System.Drawing.Imaging.ImageFormat.Jpeg); //save bitmap into memory stream in jpeg format System.Drawing.Image QR_Jpeg = System.Drawing.Image.FromStream(streamQR);// save memory stream to image file
//XImage xImage = XImage.FromGdiPlusImage(QR_Jpeg); // <-- Removed
gfx = XGraphics.FromPdfPage(page);
gfx.DrawImage(XImage.FromStream(streamQR), 0, 0, 100, 100); // <-- Added
//DrawImage(gfx, xImage, 0, 0, 100, 100); //This is not working // <-- Removed
QRCode_BMP.Dispose();
streamQR.Close();
gfx.Dispose();
For general usage of streams for XGraphics.DrawImage (library PDFSharp) here's some code I use to print SVG vector path data to PDF:
System.Windows.Shapes.Path path = new System.Windows.Shapes.Path();
// YouTube like button SVG vector path data:
path.Data = Geometry.Parse("M12.42,14A1.54,1.54,0,0,0,14,12.87l1-4.24C15.12,7.76,15,7,14,7H10l1.48-3.54A1.17,1.17,0,0,0,10.24,2a1.49,1.49,0,0,0-1.08.46L5,7H1v7ZM9.89,3.14A.48.48,0,0,1,10.24,3a.29.29,0,0,1,.23.09S9,6.61,9,6.61L8.46,8H14c0,.08-1,4.65-1,4.65a.58.58,0,0,1-.58.35H6V7.39ZM2,8H5v5H2Z");
// Visual check of the path:
// https://yqnn.github.io/svg-path-editor/
// Color area bordered through path of SVG vector:
path.Fill = new SolidColorBrush(Colors.Black);
// Upscale path, if final image is blurry:
double scale = 2;
path.RenderTransform = new ScaleTransform(scale, scale);
Rect bounds = path.Data.GetRenderBounds(null);
// Increase render bounds (here: "+ 4"), if parts of the path in the final image are cut off (test it with "scale = 1" before upscaling):
bounds.Width = (bounds.Width + 4) * scale;
bounds.Height = (bounds.Height + 4) * scale;
path.Measure(bounds.Size);
path.Arrange(bounds);
RenderTargetBitmap bitmap = new RenderTargetBitmap(
(int)bounds.Width, (int)bounds.Height, 96, 96, PixelFormats.Pbgra32);
bitmap.Render(path);
// Transparent areas are replaced with black pixels when using a "BmpBitmapEncoder", so instead use a "PngBitmapEncoder":
PngBitmapEncoder encoderPng = new PngBitmapEncoder();
encoderPng.Frames.Add(BitmapFrame.Create(bitmap));
using (MemoryStream stream = new MemoryStream())
{
encoderPng.Save(stream);
// Draw image to PDF using "XGraphics.DrawImage":
gfx.DrawImage(XImage.FromStream(stream), 10, 100, 14.05, 12.05);
}

C# Save Bitmap as PDF With iTextSharp

The following code creates a bitmap from a control on the form, and then shows a save dialog to save as a JPEG. Can anyone help with the code to save the Bitmap bm as a PDF with iTextSharp?
Bitmap bm = null;
bm = new Bitmap(this.RCofactorTBS.SelectedTab.Width, this.RCofactorTBS.SelectedTab.Height);
this.RCofactorTBS.SelectedTab.DrawToBitmap(bm, this.RCofactorTBS.SelectedTab.ClientRectangle);
SaveFileDialog dialog = new SaveFileDialog();
dialog.Filter = "JPEG|*.jpeg";
dialog.Title = "Save Test As Jpeg";
dialog.ShowDialog();
if (dialog.FileName != "" && bm != null)
{
bm.Save(dialog.FileName);
}
You can try this
System.Drawing.Image image = System.Drawing.Image.FromFile("Your image file path");
Document doc = new Document(PageSize.A4);
PdfWriter.GetInstance(doc, new FileStream("image.pdf", FileMode.Create));
doc.Open();
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image, System.Drawing.Imaging.ImageFormat.Jpeg);
doc.Add(pdfImage);
doc.Close();
Referenced from here
public void exportarPDF(Bitmap img){
// System.Drawing.Image image = System.Drawing.Image.FromFile("C://snippetsource.jpg"); // Here it saves with a physical file
System.Drawing.Image image = img; //Here I passed a bitmap
Document doc = new Document(PageSize.A4);
PdfWriter.GetInstance(doc, new FileStream("C://image.pdf", FileMode.Create));
doc.Open();
iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(image,
System.Drawing.Imaging.ImageFormat.Jpeg);
doc.Add(pdfImage);
doc.Close();
}

Categories