c# Bitmap.Save A generic error occurred in GDI+ windows application - c#

I am doing OCR application. I have this error when I run the system which the system will save the picturebox3.image into a folder.
//When user is selecting, RegionSelect = true
private bool RegionSelect = false;
private int x0, x1, y0, y1;
private Bitmap bmpImage;
private void loadImageBT_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog open = new OpenFileDialog();
open.InitialDirectory = #"C:\Users\Shen\Desktop";
open.Filter = "Image Files(*.jpg; *.jpeg)|*.jpg; *.jpeg";
if (open.ShowDialog() == DialogResult.OK)
{
singleFileInfo = new FileInfo(open.FileName);
string dirName = System.IO.Path.GetDirectoryName(open.FileName);
loadTB.Text = open.FileName;
pictureBox1.Image = new Bitmap(open.FileName);
bmpImage = new Bitmap(pictureBox1.Image);
}
}
catch (Exception)
{
throw new ApplicationException("Failed loading image");
}
}
//User image selection Start Point
private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
{
RegionSelect = true;
//Save the start point.
x0 = e.X;
y0 = e.Y;
}
//User select image progress
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
//Do nothing it we're not selecting an area.
if (!RegionSelect) return;
//Save the new point.
x1 = e.X;
y1 = e.Y;
//Make a Bitmap to display the selection rectangle.
Bitmap bm = new Bitmap(bmpImage);
//Draw the rectangle in the image.
using (Graphics g = Graphics.FromImage(bm))
{
g.DrawRectangle(Pens.Red, Math.Min(x0, x1), Math.Min(y0, y1), Math.Abs(x1 - x0), Math.Abs(y1 - y0));
}
//Temporary display the image.
pictureBox1.Image = bm;
}
//Image Selection End Point
private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
{
// Do nothing it we're not selecting an area.
if (!RegionSelect) return;
RegionSelect = false;
//Display the original image.
pictureBox1.Image = bmpImage;
// Copy the selected part of the image.
int wid = Math.Abs(x0 - x1);
int hgt = Math.Abs(y0 - y1);
if ((wid < 1) || (hgt < 1)) return;
Bitmap area = new Bitmap(wid, hgt);
using (Graphics g = Graphics.FromImage(area))
{
Rectangle source_rectangle = new Rectangle(Math.Min(x0, x1), Math.Min(y0, y1), wid, hgt);
Rectangle dest_rectangle = new Rectangle(0, 0, wid, hgt);
g.DrawImage(bmpImage, dest_rectangle, source_rectangle, GraphicsUnit.Pixel);
}
// Display the result.
pictureBox3.Image = area;
** ERROR occuer here!!!!!**
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg"); // error line occcur
singleFileInfo = new FileInfo("C:\\Users\\Shen\\Desktop\\LenzOCR\\TempFolder\\tempPic.jpg");
}
private void ScanBT_Click(object sender, EventArgs e)
{
var folder = #"C:\Users\Shen\Desktop\LenzOCR\LenzOCR\WindowsFormsApplication1\ImageFile";
DirectoryInfo directoryInfo;
FileInfo[] files;
directoryInfo = new DirectoryInfo(folder);
files = directoryInfo.GetFiles("*.jpg", SearchOption.AllDirectories);
var processImagesDelegate = new ProcessImagesDelegate(ProcessImages2);
processImagesDelegate.BeginInvoke(files, null, null);
//BackgroundWorker bw = new BackgroundWorker();
//bw.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
//bw.RunWorkerAsync(bw);
//bw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(backgroundWorker1_RunWorkerCompleted);
}
private void ProcessImages2(FileInfo[] files)
{
var comparableImages = new List<ComparableImage>();
var index = 0x0;
foreach (var file in files)
{
if (exit)
{
return;
}
var comparableImage = new ComparableImage(file);
comparableImages.Add(comparableImage);
index++;
}
index = 0;
similarityImagesSorted = new List<SimilarityImages>();
var fileImage = new ComparableImage(singleFileInfo);
for (var i = 0; i < comparableImages.Count; i++)
{
if (exit)
return;
var destination = comparableImages[i];
var similarity = fileImage.CalculateSimilarity(destination);
var sim = new SimilarityImages(fileImage, destination, similarity);
similarityImagesSorted.Add(sim);
index++;
}
similarityImagesSorted.Sort();
similarityImagesSorted.Reverse();
similarityImages = new BindingList<SimilarityImages>(similarityImagesSorted);
var buttons =
new List<Button>
{
ScanBT
};
if (similarityImages[0].Similarity > 70)
{
con = new System.Data.SqlClient.SqlConnection();
con.ConnectionString = "Data Source=SHEN-PC\\SQLEXPRESS;Initial Catalog=CharacterImage;Integrated Security=True";
con.Open();
String getFile = "SELECT ImageName, Character FROM CharacterImage WHERE ImageName='" + similarityImages[0].Destination.ToString() + "'";
SqlCommand cmd2 = new SqlCommand(getFile, con);
SqlDataReader rd2 = cmd2.ExecuteReader();
while (rd2.Read())
{
for (int i = 0; i < 1; i++)
{
string getText = rd2["Character"].ToString();
Action showText = () => ocrTB.AppendText(getText);
ocrTB.Invoke(showText);
}
}
con.Close();
}
else
{
MessageBox.Show("No character found!", "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
#endregion

Since it has been a while, I'm hoping you found your answer, but I'm going to guess that you needed to set the file format when you're saving a jpeg:
area.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
Past that, I can't remember if the picturebox control is double buffered or not which could be the problem (if it's not, you might not be able to access it for saving purposes while it is being rendered, but if you make a copy of area before setting the picturebox3.Image property that would fix that issue):
Bitmap SavingObject=new Bitmap(area);
picturebox3.Image=area;
SavingObject.Save(#"C:\Users\Shen\Desktop\LenzOCR\TempFolder\tempPic.jpg",System.Drawing.Imaging.ImageFormat.Jpeg);
Anyway, I hope you ended up finding your solution (considering it's been a couple months since this was posted).

This looks like a copy of this question:
c# A generic error occurred in GDI+
Same code, same error, same author.
Can't see any difference. But maybe I'm missing something.

Related

improve image quality of cropped image c#

i created a windows form c# application. It has feature to crop image. After cropping image. it show preview in other picturebox. My problem is the cropping place little bit blur in picture box. .Here is picture to understand what i meant...I want to fix it
enter image description here
here is the code i used.
{
string root = #"C:\FuelPass";
// If directory does not exist, create it.
if (!System.IO.Directory.Exists(root))
{
System.IO.Directory.CreateDirectory(root);
}
Bitmap bmp = new Bitmap(previewimg.Width, previewimg.Height);
previewimg.DrawToBitmap(bmp, new Rectangle(0, 0, previewimg.Width, previewimg.Height));
pictureBox2.DrawToBitmap(bmp, new Rectangle(pictureBox2.Location.X - previewimg.Location.X, pictureBox2.Location.Y - previewimg.Location.Y, pictureBox2.Width, pictureBox2.Height));
String savename="";
// DateTime dt = new DateTime();
// bmp.Save(#"C:\Fuelpass\" +dt.ToString()+ " .jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Save(#"C:\Fuelpass\output-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
Form2 f2 = new Form2();
f2.Show();
// MessageBox.Show("Image has been saved");
// SaveFileDialog dialog = new SaveFileDialog();
// dialog.Filter = "JPG(*.JPG)|*.jpg";
// if (dialog.ShowDialog() == DialogResult.OK)
// {
// previewimg.Image.Save(dialog.FileName);
// pictureBox2.Image.Save(dialog.FileName);
// }
// }
}
private void PictureBoxLoad_MouseUp_1(object sender, MouseEventArgs e)
{
//pictureBox1.Image.Clone();
try
{
if (IsMouseDown == true)
{
LocationX1Y1 = e.Location;
IsMouseDown = false;
if (Rect != null)
{
Bitmap bit = new Bitmap(PictureBoxLoad.Image, PictureBoxLoad.Width, PictureBoxLoad.Height);
Bitmap cropImg = new Bitmap(Rect.Width, Rect.Height);
Graphics g = Graphics.FromImage(cropImg);
g.DrawImage(bit, 0, 0, Rect, GraphicsUnit.Pixel);
pictureBox2.Image = cropImg;
}
}
}
catch { }
}
private Rectangle GetRect()
{
Rect = new Rectangle();
Rect.X = Math.Min(LocationXY.X, LocationX1Y1.X);
Rect.Y = Math.Min(LocationXY.Y, LocationX1Y1.Y);
Rect.Width = Math.Abs(LocationXY.X - LocationX1Y1.X);
Rect.Height = Math.Abs(LocationXY.Y - LocationX1Y1.Y);
return Rect;
}

Picturebox duplicating value

I am working on a little program that starts taking pictures in the moment you click on a button. Also it can be ended earlier clicking another button.
The little bug that I am having is that I use a timer to process each time you go throw it since you hit the start button in a 1000ms interval, the problem comes when the first process finishes, the next process you start will duplicate the value of a progressbar x2 forever until you close the app.
namespace Fotos
{
public partial class Fotos : Form
{
private static string Path = #"C:\Fotos\";
//private static string Agua = #"C:\Marca de Agua\";
private bool HayDispositivos, terminado;
private string nombre;
private int i = 0, j = 0, z = 0, eleccion;
private FilterInfoCollection MisDispositivos;
private VideoCaptureDevice miWebcam;
private MagickImageCollection gif = new MagickImageCollection();
public Fotos()
{
InitializeComponent();
}
private ImageCodecInfo GetEncoder(ImageFormat format)
{
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
foreach (ImageCodecInfo codec in codecs)
{
if (codec.FormatID == format.Guid)
{
return codec;
}
}
return null;
}
private void Creador()
{
CreacionGif cg = new CreacionGif(gif, nombre);
cg.ShowDialog();
}
private void MarcaAgua(PictureBox picturebox1)
{
RectangleF angulo = new RectangleF(1350, 975, 535, 90); //rectf for My Text
using (Graphics g = Graphics.FromImage(picturebox1.Image))
{
//g.DrawRectangle(new Pen(Color.Red, 2), 655, 460, 535, 90);
g.SmoothingMode = SmoothingMode.AntiAlias;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
StringFormat sf = new StringFormat();
sf.Alignment = StringAlignment.Center;
sf.LineAlignment = StringAlignment.Center;
g.DrawString(DateTime.Now.ToString(), new Font("Tahoma", 32, FontStyle.Bold), Brushes.White, angulo, sf);
EncoderParameters myEncoderParameters = new EncoderParameters(1);
ImageCodecInfo jpgEncoder = GetEncoder(ImageFormat.Jpeg);
Encoder myEncoder = Encoder.Quality;
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 30L);
myEncoderParameters.Param[0] = myEncoderParameter;
if (progressBar1.Value == 0)
{
j = 0;
}
picturebox1.Image.Save(Path + textBoxNombreFoto.Text + "_" + i + ".jpg", jpgEncoder, myEncoderParameters);
gif.Add(Path + textBoxNombreFoto.Text + "_" + i + ".jpg");
gif[j].AnimationDelay = 200;
j++;
g.Dispose();
sf.Dispose();
/* using (Image image = pictureBox1.Image)
using (Image watermarkImage = Image.FromFile(Agua +"fecha.jpg"))
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)));
image.Save(Path + i +".jpg");*/
}
}
private void Form_Load(object sender, EventArgs e)
{
CargaDispositivos();
}
public void CargaDispositivos()
{
MisDispositivos = new FilterInfoCollection(FilterCategory.VideoInputDevice);
if (MisDispositivos.Count > 0)
{
HayDispositivos = true;
for (int i = 0; i < MisDispositivos.Count; i++)
comboBox1.Items.Add(MisDispositivos[i].Name.ToString());
comboBox1.Text = MisDispositivos[0].Name.ToString();
}
else HayDispositivos = false;
}
private void CerrarWebcam()
{
if (miWebcam != null && miWebcam.IsRunning)
{
miWebcam.SignalToStop();
miWebcam = null;
}
}
private void Capturando(object sender, NewFrameEventArgs eventArgs)
{
if(terminado == false)
{
Bitmap Imagen = (Bitmap)eventArgs.Frame.Clone();
pictureBox1.Image = Imagen;
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
CerrarWebcam();
}
private void foto_Click(object sender, EventArgs e)
{
if (miWebcam != null && miWebcam.IsRunning && (radioButton1.Checked == true || radioButton2.Checked == true) && textBoxNombreFoto.TextLength > 0)
{
timer1.Enabled = true;
timer1.Start();
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timer1_Tick);
terminado = false;
if(radioButton1.Checked == true)
{
eleccion = 18;
progressBar1.Maximum = 1800;
}
else
{
eleccion = 36;
progressBar1.Maximum = 3600;
}
}
else
{
MessageBox.Show("Por favor revisa que todos los campos estén rellenos");
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
CerrarWebcam();
int i = comboBox1.SelectedIndex;
string nombreVideo = MisDispositivos[i].MonikerString;
miWebcam = new VideoCaptureDevice(nombreVideo);
miWebcam.NewFrame += new NewFrameEventHandler(Capturando);
miWebcam.Start();
}
private void finFoto_Click(object sender, EventArgs e)
{
MarcaAgua(pictureBox1);
terminado = true;
}
private void timer1_Tick(object sender, EventArgs e)
{
if (progressBar1.Value % 30 == 0 && progressBar1.Value <= eleccion && terminado != true || progressBar1.Value == 0)
{
miWebcam.NewFrame += new NewFrameEventHandler(Capturando);
MarcaAgua(pictureBox1);
z++;
}
if (progressBar1.Value < eleccion && terminado != true)
{
progressBar1.Value++;
i++;
}
textBoxTiempo.Text = progressBar1.Value.ToString();
textBoxTiempo.Update();
if ((terminado == true || progressBar1.Value >= eleccion) && i!=0)
{
timer1.Stop();
timer1.Dispose();
progressBar1.Dispose();
progressBar1.Value = 0;
nombre = textBoxNombreFoto.Text;
Creador();
i = 0;
MessageBox.Show("Proceso Terminado con Éxito");
}
}

How do I center an image when I am merging it on to another image?

I found some code online to merge images. I set it up and worked it out. I finally got it to work but the images that I am merging onto the blank image is not centered.
Here is the how it looks:
Here is my code:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void btnSelectImage_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
openFileDialog.Filter = "Images (*.jpg, *.jpeg, *.png)|*.*";
openFileDialog.FilterIndex = 1;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
txtFileLoc.Text = openFileDialog.FileName;
System.Drawing.Image img = System.Drawing.Image.FromFile(txtFileLoc.Text);
txtImgWidth.Text = img.Width.ToString();
txtImgHeight.Text = img.Height.ToString();
}
}
private void button1_Click(object sender, EventArgs e)
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
txtOutputPath.Text = fbd.SelectedPath;
//string[] files = System.IO.Directory.GetFiles(fbd.SelectedPath);
//System.Windows.Forms.MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
}
}
}
private void btnResize_Click(object sender, EventArgs e)
{
DateTime time = DateTime.Now;
string format = "MMMddyyy";
string imgdate = time.ToString(format);
int Height = Convert.ToInt32(txtNewHeight.Text);
int Width = Convert.ToInt32(txtNewWidth.Text);
Image resultImage = new Bitmap(Height, Width, PixelFormat.Format24bppRgb);
using (Graphics grp = Graphics.FromImage(resultImage))
{
grp.FillRectangle(
Brushes.White, 0, 0, Width, Height);
resultImage.Save(txtOutputPath.Text + #"\" + imgdate + ".jpeg", System.Drawing.Imaging.ImageFormat.Jpeg);
Image img = Image.FromFile(txtFileLoc.Text);
}
Image playbutton;
try
{
playbutton = Image.FromFile(txtFileLoc.Text);
}
catch (Exception ex)
{
return;
}
Image frame;
try
{
frame = resultImage;
}
catch (Exception ex)
{
return;
}
using (frame)
{
using (var bitmap = new Bitmap(Width, Height))
{
using (var canvas = Graphics.FromImage(bitmap))
{
canvas.InterpolationMode = InterpolationMode.HighQualityBicubic;
canvas.DrawImage(frame,
new Rectangle(0,
0,
Width,
Height),
new Rectangle(0,
0,
frame.Width,
frame.Height),
GraphicsUnit.Pixel);
canvas.DrawImage(playbutton,
(bitmap.Width / 2) - (playbutton.Width / 2),
(bitmap.Height / 2) - (playbutton.Height / 2));
canvas.Save();
}
try
{
bitmap.Save(txtOutputPath.Text + #"\" + imgdate + ".png", System.Drawing.Imaging.ImageFormat.Png);
}
catch (Exception ex) { }
}
}
}
}
In order to center an image when drawing on top of another image you need to calculate the position of an image (X,Y) which can be done as following:
int x = (bitmap.Width - image.Width) / 2;
int x = (bitmap.Height - image.Height) / 2;
Then you can just draw your image with
canvas.DrawImage(image, x, y, image.Width, image.Height);
Notice, this approach allows you to center an image regardless of whether it's smaller than the original bitmap or larger. When calculating the (X,Y) an one pixel rounding inaccuracy may occur so it would be beneficial to use Math.Round to correct that.

Panel.controls.Clear invalid parameter error

Foreach img in a folder i paint a picturebox on a panel, when i try to repaint the pictureboxes (after i remove one) the 'panel.controls.clear();' line gives a error:
Blockquote An unhandled exception of type 'System.ArgumentException' occurred in System.Drawing.dll Additional information: invalid parameter.
private void removeScreenshot_Click(object sender, EventArgs e)
{
Button btn = sender as Button;
PictureBox pb = btn.Parent as PictureBox;
string imgString = pb.Tag.ToString()
pb.BackgroundImage.Dispose();
pb.Image.Dispose();
try
{
File.Delete(imgString);
pb.Dispose();
}
catch (Exception ex)
{
Console.WriteLine("Cannot delete img: " + ex);
}
reload();
}
Below reload() function:
private void reload()
{
bool firstImg = true;
string[] fileList = Directory.GetFiles(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\screenshots");
List<string> listOfStrings = new List<string>(fileList);
string supportedExtensions = "*.jpg,*.gif,*.png,*.bmp,*.jpe,*.jpeg";
listOfStrings.Reverse();
screenShotPanel.Controls.Clear();
if (listOfStrings.Count > 0)
{
foreach (string imgString in listOfStrings)
{
string extension = System.IO.Path.GetExtension(imgString);
if (supportedExtensions.Contains(extension))
{
PictureBox pb = new PictureBox();
pb.Click += new EventHandler(click_pb);
pb.MouseHover += new EventHandler(mouseHover_pb);
pb.MouseLeave += new EventHandler(mouseLeave_pb);
pb.Height = 100;
pb.Width = 100;
pb.Location = new Point(x, y);
Bitmap src = Image.FromFile(imgString) as Bitmap;
Bitmap cropped = CropBitmap(src, pb.Width, pb.Height);
Button removeScreenshot = new Button();
removeScreenshot.Height = 20;
removeScreenshot.Width = 20;
removeScreenshot.Location = new Point(80, 0);
removeScreenshot.BackColor = Color.Transparent;
removeScreenshot.ForeColor = Color.Transparent;
removeScreenshot.FlatStyle = FlatStyle.Flat;
removeScreenshot.FlatAppearance.BorderSize = 0;
removeScreenshot.MouseHover += new EventHandler(mouseHover_removeButton);
removeScreenshot.MouseLeave += new EventHandler(mouseLeave_removeButton);
removeScreenshot.Click += new EventHandler(removeScreenshot_Click);
pb.Controls.Add(removeScreenshot);
pb.BackgroundImage = src;
if (firstImg)
{
pictureBox.Image = src;
firstImg = false;
}
pb.Image = cropped;
pb.Tag = imgString;
pb.Name = Path.GetFileName(imgString);
screenShotPanel.Controls.Add(pb);
x = x + 120;
}
}
}
else
{
pictureBox.Image = null;
pictureBox.BackgroundImage = null;
}
}
The solution of the question is fixed by the following code:
using (var bmpTemp = new Bitmap(imgString))
{
src = new Bitmap(bmpTemp);
}
As replacement of this code:
Bitmap src = Image.FromFile(imgString) as Bitmap;

Obtain full-page screenshot from WebBrower component

I am attempting to capture a full-page screenshot of any website a user is viewing using the WebBrowser component.
At present, I am able to only able to capture what a user is viewing from within the WebBrowser. However, the screenshot image created is the size of the webpage. For example, below is a (half-sized) screenshot of the BBC website, the black area is actually saved transparent but I've filled it black for visibility.
I have seen solutions where a new WebBrowser instance is used to fetch a fullpage snapshot. However, I need the screenshot to be exactly of the page as the user is viewing it at the time, much like how the full-page screenshot works in Firefox.
My code below that generated the above image:
private void button1_Click(object sender, EventArgs e)
{
while (webBrowser1.ReadyState != WebBrowserReadyState.Complete)
{
Application.DoEvents();
}
int scrollWidth = 0;
int scrollHeight = 0;
scrollHeight = webBrowser1.Document.Body.ScrollRectangle.Height;
scrollWidth = webBrowser1.Document.Body.ScrollRectangle.Width;
webBrowser1.Size = new Size(scrollWidth, scrollHeight);
Bitmap bm = new Bitmap(scrollWidth, scrollHeight);
webBrowser1.DrawToBitmap(bm, new Rectangle(0, 0, bm.Width, bm.Height));
bm.Save(#"D:\Screenshots\test.png", ImageFormat.Png);
}
I've got a good working one..
private void button1_Click(object sender, EventArgs e)
{
using (FileDialog fd = new SaveFileDialog())
{
fd.Filter = "Image (*.png)|*.png";
if (fd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
new WebPageSnap(webBrowser1.Url.ToString(), fd.FileName);
//might take 3 or 4 seconds to save cauz it has to load again.
}
}
}
class WebPageSnap
{
WebBrowser wb;
string outFile;
public WebPageSnap(string url, string outputFile)
{
wb = new WebBrowser();
wb.ProgressChanged += wb_ProgressChanged;
outFile = outputFile;
wb.ScriptErrorsSuppressed = true;
wb.ScrollBarsEnabled = false;
wb.Navigate(url);
}
void wb_ProgressChanged(object sender, WebBrowserProgressChangedEventArgs e)
{
if (e.CurrentProgress == e.MaximumProgress)
{
wb.ProgressChanged -= wb_ProgressChanged;
try
{
int scrollWidth = 0;
int scrollHeight = 0;
scrollHeight = wb.Document.Body.ScrollRectangle.Height;
scrollWidth = wb.Document.Body.ScrollRectangle.Width;
wb.Size = new Size(scrollWidth, scrollHeight);
Bitmap bitmap = new Bitmap(wb.Width, wb.Height);
for (int Xcount = 0; Xcount < bitmap.Width; Xcount++)
for (int Ycount = 0; Ycount < bitmap.Height; Ycount++)
bitmap.SetPixel(Xcount, Ycount, Color.Black);
wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
bitmap.Save(outFile, ImageFormat.Png);
}
catch { }
}
}
}
.
;Here's the result
.

Categories