Storing and retrieving images from Database - c#

I created an ASP.NET/C# application to upload an image to MySQL database. The process executes without any error but for whatever image I upload I am getting output of 100x100 white image. The procedure I followed is.
1) Created a database with field picture and type Binary(255).
2) Uploaded an image as cmd.Parameters.Add("#picture", OdbcType.Binary, 255).Value = FileUpload1.FileBytes;
3) Doing above a new record is being inserted and a value something of below kind is generated.
89504e470d0a1a0a0000000d49484452000002600000010008020000009b155d400000100049444154789cd4dc05745b57a2377a15c26088d99651b2248b999959b2c0966cc9cccccc8e1ddb01439899d3a4499a869999e33037d0340d34d4b4d5dbaee7e6f6b5337367eefad67bf3adf55f676dd98e221f6b9ddffeef738e20db5cbf826c77fd3638d8eafa6587ebd79daedfc0f6afd9eefae5ab372fd6bf7db9e5e7b7075dae4daf5e1c76b98ebb5cfb7ef935a5b31b028b32ea53f6ec3a77efe60fb919156e34222b297ee3aedd2e97ebe6dd870b96acd8b0efc0891bb76ae7ce8ba9a8dc70f1f2c917afaeb95ce75c1f276cd988b0180329c4c4aaf2d2
//--------------- Uploading module completed -----------------//
1) Created a ASPX page with
<asp:Image ID="img" runat="server" ImageUrl="~/MyImage.ashx" />
2) Left ASPX.CS file without any code
3) Added a ASHX file with
<%# WebHandler Language="C#" Class="MyImage" %>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Drawing.Imaging;
public class MyImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "image/png";
var data = "89504e470d0a1a0a0000000d49484452000002600000010008020000009b155d400000100049444154789cd4dc05745b57a2377a15c26088d99651b2248b999959b2c0966cc9cccccc8e1ddb01439899d3a4499a869999e33037d0340d34d4b4d5dbaee7e6f6b5337367eefad67bf3adf55f676dd98e221f6b9ddffeef738e20db5cbf826c77fd3638d8eafa6587ebd79daedfc0f6afd9eefae5ab372fd6bf7db9e5e7b7075dae4daf5e1c76b98ebb5cfb7ef935a5b31b028b32ea53f6ec3a77efe60fb919156e34222b297ee3aedd2e97ebe6dd870b96acd8b0efc0891bb76ae7ce8ba9a8dc70f1f2c917afaeb95ce75c1f276cd988b0180329c4c4aaf2d2";
var buffer = StringToByteArray(data);
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
}
private byte[] StringToByteArray(string hex)
{
return Enumerable
.Range(0, hex.Length)
.Where(x => x % 2 == 0)
.Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
.ToArray();
}
public bool IsReusable
{
get { return false; }
}
}
By executing this code a white 100x100 image is being displayed in output for any colorful input. I double checked ContentType and uploaded various images of various sizes and formats but whatever I do I am getting an output of same White image. What's wrong in my code? any corrections?

You can try saving the image as a Base64 encoded string, then converting it back to an image when you want it to render on your web page.
Here is a link on how to do it.
Base64String to Image and visa versa
Here is a link to how I used it in my project, not quite from an image or from a database but the concept is the same.
When using my method in your webpage you'll use
<img src="${downloadurl}" />

A 255 byte binary field type is not going to be large enough to handle anything except the very tiniest of images. Check the size of the files you are uploading and re-size the field accordingly.

I have this code in an ashx which pulls image data and displays it from an MSSQL database
public void ProcessRequest(HttpContext context)
{
Guid picid;
if (context.Request.QueryString["picid"] != null)
picid = new Guid(context.Request.QueryString["picid"]);
else
throw new ArgumentException("No parameter specified");
context.Response.ContentType = "image/jpeg";
Stream strm = ShowPicImage(picid);
byte[] buffer = new byte[4096];
int byteSeq = strm.Read(buffer, 0, 4096);
while (byteSeq > 0)
{
context.Response.OutputStream.Write(buffer, 0, byteSeq);
byteSeq = strm.Read(buffer, 0, 4096);
}
}
public Stream ShowPicImage(Guid piciddata)
{
ProductPicture pictureData = new ProductPicture("ProductPictureID", piciddata);
object img = pictureData.Data;
try
{
return new MemoryStream((byte[])img);
}
catch
{
return null;
}
}
i don't know if it's something you can try for your problem. (Where the pictureData.Data property type is a byte[] and the relevant database column is a varbinary(max))
updated answer
You may also want to consider storing the data in the database as a BLOB

Related

Why Image.Save() in C# does not always give the same serialized result and how to serialize an image in a deterministic way?

I serialize images using the following code:
public static string SerializeImage(Image image)
{
using (MemoryStream memoryStream = new MemoryStream())
{
image.Save(memoryStream, image.RawFormat);
return Convert.ToBase64String(memoryStream.ToArray());
}
}
and deserialize the images by doing the following
public static Image DeserializeImage(string serializedImage)
{
byte[] imageAsBytes = Convert.FromBase64String(serializedImage);
using (MemoryStream memoryStream = new MemoryStream(imageAsBytes, 0, imageAsBytes.Length))
{
memoryStream.Write(imageAsBytes, 0, imageAsBytes.Length);
return Image.FromStream(memoryStream, true);
}
}
If I have an image and does
string serializedImage1 = SerializeImage(image);
Image deserializedImage = DeserializeImage(serializedImage1);
string serializedImage2 = SerializeImage(deserializedImage );
Then
serializedImage1 == serializedImage2;
as expected. But it is not always the case.
If I serialize an image on Process 1, and then redeserialize and reserialize it on Process 2, then the result of the reserialization on Process 2 is not the same as on the Process 1. Everything works, but a few bytes in the beginning of the serialization are different.
Worst, if I do the same thing on 2 different dll (or thread, I'm not sure), it seems the serialization result is not the same too. Again, the serialization/deserialization works, but a few bytes are different.
The image the first time is loaded with the following function :
public static Image GetImageFromFilePath(string filePath)
{
var uri = new Uri(filePath);
var bitmapImage = new BitmapImage(uri);
bitmapImage.Freeze();
using (var memoryStream = new MemoryStream())
{
var pngBitmapEncoder = new PngBitmapEncoder();
pngBitmapEncoder.Frames.Add(BitmapFrame.Create(bitmapImage));
pngBitmapEncoder.Save(memoryStream);
Image image = Image.FromStream(memoryStream);
return image;
}
}
Note however that it happens even if the image is loaded twice with the DeserializeImage() function.
The tests I have done are with ImageFormat.Jpeg and ImageFormat.Png.
First question, why it does this ? I would have expected the result to be always the same, but I suppose some salt is used when doing the Image.Save().
Second question : I want to have a deterministic way to serialize an image, keeping the image format intact. The goal is to save the image in a DB and also to compare serialized images to know if it already exists in the system where this function is used.
Well, I discovered while trying to solve this that a png or jpeg Image object inside C# has some metadata associated to it and doing what I was doing is just not a reliable way to compare images.
The solution I used was derived from this link
https://insertcode.wordpress.com/2014/05/13/compare-content-of-two-files-images-in-c/
So what I do finally is save the images inside the system with the SerializeImage(Image image) function previously described, and when I want to consume it I deserialize it with the DeserializeImage(string serializedImage) function previously described. But when I want to compare images I use the following functions
public static bool ImagesAreEqual(Image image1, Image image2)
{
string image1Base64Bitmap = GetImageAsBase64Bitmap(image1);
string image2Base64Bitmap = GetImageAsBase64Bitmap(image2);
return image1Base64Bitmap.Equals(image2Base64Bitmap);
}
public static string GetImageAsBase64Bitmap(Image image)
{
using (var memoryStream = new MemoryStream())
{
using (var bitmap = new Bitmap(image))
{
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
}
return Convert.ToBase64String(memoryStream.ToArray());
}
}
That convert the image to raw bitmap before comparing them.
This does a perfect job for me in all my needed cases : the formats of the images are saved/restored correctly, and I can compare them between them to check if they are the same without having to bother with the possibly different serialization.

Displaying a byte[] in an image control

So I collect a varbinary(MAX) value from a database where an image is stored.
It gets converted to byte[], then the aim is to display this in an image control.
This is where I read from the database
public TemplateData(SqlDataReader dr)
{
initialiseData();
if (dr.HasRows)
{
Logo = (byte[])dr["Logo"];
//Logo = dr["Logo"].ToString();
TemplateId = dr["TemplateId"].ToString();
Comment = dr["Comment"].ToString();
SchemeCode = dr["SchemeCode"].ToString();
Version = dr["Version"].ToString();
}
}
This is where the values are displayed into the corresponding controls
protected void ddSchemeCode_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddSchemeCode.SelectedIndex > 0)
{
// Existing Data to load from database
TemplateData temp = DataClass.ReturnData(ddSchemeCode.SelectedItem.Text);
if (temp != null)
{
txtVersion.Text = temp.Version;
txtComment.Text = temp.Comment;
txtSchemeCode.Text = temp.SchemeCode;
txtTemplateId.Text = temp.TemplateId;
img.Src = temp.Logo;
}
So at the moment I am passing a byte[] into the source of an image control, where it would instead like a string. I've tried converting it to a string with Convert.ToBase64String(Logo) and ToString(Logo) but these do not work.
Any help is greatly appreciated. Cheers guys and gals.
Try converting the byte array to image and assign it to picturebox as below,
try
{
using (MemoryStream mStream = new MemoryStream())
{
// where pData is your byte array
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Image originalImage = Image.FromStream(mStream);
picBox.Image = originalImage;
}
}
catch (Exception ex)
{
}
Hope it helps.
As you may have noticed, you cannot "print" an image in a webpage. You need to get a little bit creative now.
What you want to look into is Response.BinaryWrite. More information about that, here: https://msdn.microsoft.com/en-us/library/system.web.httpresponse.binarywrite%28v=vs.110%29.aspx
You will probably also need a generic ashx handler. Here is an example of how to show a picture using a handler: http://www.dotnetperls.com/ashx
My suggestion would be to store the logo as a byte[] into the http session. Put the source of the image to theHttpHandlerYourGonnaCreate.ashx. You can then binary write the byte[] you've stored into the session there.
Hope this helps!
As Michael shows here, you can convert the byte array to a Bitmap object with something like this:
Bitmap bitmap = null;
using (MemoryStream imageStream = new MemoryStream(imageData))
{
bitmap = new Bitmap(imageStream);
}
It isn't entirely clear what you're using for a control to show the image, but any control that can display an image should be able to take a Bitmap or Image object.

Base64 encoded image data sent from C# to PHP yields broken displayed image

Yesterday I asked a question and implemented an answer concerning how to send image data from a C# application to a PHP web page ready to receive the POST data, decode it, and display the image.
Here's the C# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Net;
using System.Collections.Specialized;
namespace ConsoleApplication1
{
class Program
{
public static void Main()
{
// Load a image
System.Drawing.Image myImage = GetImage("http://upload.wikimedia.org/wikipedia/commons/5/5b/Ultraviolet_image_of_the_Cygnus_Loop_Nebula_crop.jpg");
// Convert to base64 encoded string
string base64Image = ImageToBase64(myImage, System.Drawing.Imaging.ImageFormat.Jpeg);
// Post image to upload handler
using (WebClient client = new WebClient())
{
byte[] response = client.UploadValues("www.myurl.com", new NameValueCollection()
{
{ "myImageData", base64Image }
});
Console.WriteLine("Server Said: " + System.Text.Encoding.Default.GetString(response));
}
Console.ReadKey();
}
static System.Drawing.Image GetImage(string filePath)
{
WebClient l_WebClient = new WebClient();
byte[] l_imageBytes = l_WebClient.DownloadData(filePath);
MemoryStream l_stream = new MemoryStream(l_imageBytes);
return Image.FromStream(l_stream);
}
static string ImageToBase64(System.Drawing.Image image, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
}
}
And here's the PHP code:
<?php
// Handle Post
if (count($_POST))
{
// Save image to file
$imageData = base64_decode($_POST['myImageData']);
// Write Image to file
$h = fopen('test.jpg', 'w');
fwrite($h, $imageData);
fclose($h);
// Success
exit('Image successfully uploaded.');
}
// Display Image
if (file_exists('test.jpg'))
{
echo '<img src="test.jpg?_='. filemtime('test.jpg') .'" />';
}
else
{
echo "Image not uploaded yet.";
}
?>
Everything seems to work up to a certain point--I get a console message that says the image was successfully uploaded, but when I visit my webpage, I get a broken image, rather than stating the "Image not uploaded yet". From this I think I can conclude everything is at least working enough to send the data from C# to PHP--it just seems like the encoding/decoding of the image itself is not working properly. Oddly, earlier on in this project, we were doing something similar with encoding and decoding images, but the python code only works in linux--not windows. Linux would give the right image, windows only displayed a broken image with the same code.
Any ideas on what the problem is and how to fix it?
If you choose a different (smaller) image like http://upload.wikimedia.org/wikipedia/commons/thumb/9/98/Banteay_Kdei%2C_Angkor%2C_Camboya%2C_2013-08-16%2C_DD_15.JPG/640px-Banteay_Kdei%2C_Angkor%2C_Camboya%2C_2013-08-16%2C_DD_15.JPG it's working perfectly.
So I'm afraid you're reaching the upload limit for post data, which should be 8MB in PHP by default. The image you're trying to upload is 12MB and Base64 encoded it is close to 20MB.
post_max_size in the php.ini can be modified to increase the post limit. But I highly recommend switching to regular file upload. See WebClient.uploadFile (http://msdn.microsoft.com/en-us/library/36s52zhs(v=vs.110).aspx).

How to Reference HTTP Handler from UserControl

I'm a newb when it comes to creating an ASP.NET custom user control that will render and return .png charts to an ASP.NET web application.
I've created a simple sandbox project that creates an ellipse on a bitmap, renders it to a MemoryStream, and now I want to stream the output connected via an HTTP handler so as to render an asp:image in my markup page.
My problem is that I don't know how to connect the MemoryStream created in my usercontrol to the GetImage method of the http handler. I know that the GetMethod of the HTTP Handler creating a memory stream within the method isn't correct, but I don't know how to access the memorystream of the codebehind.
My prototype test project code is:
namespace ChartControl
{
public partial class ChartCtl : System.Web.UI.UserControl
{
private int imageHeight = 150;
private int imageWidth = 400;
protected void Page_Load(object sender, EventArgs e)
{
renderChart();
}
protected MemoryStream renderChart()
{
Image imgChart = new Bitmap(imageWidth, imageHeight);
Graphics g = Graphics.FromImage(imgChart);
Rectangle r = new Rectangle(0, 0, imageWidth, imageHeight);
g.DrawEllipse(Pens.Orange, g.VisibleClipBounds);
MemoryStream ms = new MemoryStream();
imgChart.Save(ms, ImageFormat.Png);
return ms;
}
}
}
My HTTP Handler is:
namespace WIChart.UserControls
{
public class ImageHandler : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.Clear();
if (!String.IsNullOrEmpty(context.Request.QueryString["id"]))
{
int id = Int32.Parse(context.Request.QueryString["id"]);
// Now we have the id, just pass it to GetImage to build the image
Image image = GetImage(id);
context.Response.ContentType = "image/png";
image.Save(context.Response.OutputStream, ImageFormat.Png);
}
else
{
context.Response.ContentType = "text/html";
context.Response.Write("<p>Valid id is required.</p>");
}
}
#region IHttpHandler Members
public bool IsReusable
{
get { return false; }
}
private Image GetImage(int id)
{
MemoryStream stream = new MemoryStream();
return Image.FromStream(stream);
}
#endregion
}
}
My .ascx page is:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="ChartCtl.ascx.cs" Inherits="ChartControl.ChartCtl" %>
<%# Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>
<div class="content-wrapper">
<div class="float-left">
<p class="site-title">
<asp:Image id="imgChart" ImageUrl="~/ImageHandler.ashx?id=1" runat="server" />
</p>
</div>
</div>
Thank you for any help that you can provide!
I couldn't understand what exactly you need here. But You can load image from user control using below code.
using System.Web;
using System.Web.UI;
using System.IO;
namespace WebApplication1
{
public class ImageHandler : Page, IHttpHandler
{
public new void ProcessRequest(HttpContext context)
{
context.Response.Clear();
ChartCtl chartCtl = (ChartCtl)LoadControl(ResolveClientUrl("ChartCtl.ascx"));
MemoryStream ms = new MemoryStream();
ms = chartCtl.renderChart(ms);
context.Response.Clear();
context.Response.ContentType = "image/jpeg";
context.Response.BinaryWrite(ReadFully(ms));
context.Response.End();
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
#region IHttpHandler Members
public new bool IsReusable
{
get { return false; }
}
#endregion
}
}
HTML-
<asp:Image ID="imgChart" ImageUrl="~/ImageHandler.ashx" runat="server" />
ChartCtrl -
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
namespace WebApplication1
{
public partial class ChartCtl : System.Web.UI.UserControl
{
private int imageHeight = 150;
private int imageWidth = 400;
public MemoryStream renderChart(MemoryStream ms)
{
Image imgChart = new Bitmap(imageWidth, imageHeight);
Graphics g = Graphics.FromImage(imgChart);
Rectangle r = new Rectangle(0, 0, imageWidth, imageHeight);
g.DrawEllipse(Pens.SteelBlue, g.VisibleClipBounds);
imgChart.Save(ms, ImageFormat.Jpeg); // save the image to the memorystream to be processed via the Image/HttpHandler
imgChart.Save(Context.Response.OutputStream, ImageFormat.Jpeg); // save to drive just to verify that image is being properly created.
return ms;
}
}
}
Web.Config [IIS 7] -
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<handlers>
<add name="ImageHandler" verb="*"
path="ImageHandler.ashx"
type="WebApplication1.ImageHandler, WebApplication1"
resourceType="Unspecified" />
</handlers>
</system.webServer>
Mem Stream to byte array conversion is from Creating a byte array from a stream
Check this link also http://www.codeproject.com/Articles/34084/Generic-Image-Handler-Using-IHttpHandler
P.S - I don't know why your code is being executed only with constructor. Without constructor I'm able to execute the code. When you are loading a web control from Handler, normal page events wouldn't get executed. We need call methods manually.
I think You need to host your website in IIS to get HTTpHandler called, I am not sure about this part.
You are coming at this a bit backwards with using your imagehandler as a page -- try to think of the page as static HTML where you are referencing an image and the answer is pretty straightforward. What you need to do is add an image tag referencing your graphic-generating handler -- ie <img src="~/MyHandler.ashx" />.
The challenge then becomes how to marshal data into the handler. There are loads of ways to handle this, the basic ones being query string variables if the data is simple or a query string with enough data so the handler can go back and load it's own data.

How do I get a bitmap of the WatiN image element?

I have some textfields processed and other elements, but I want to get the bitmap so I can save it somewhere on disk. I need to do it directly from WatiN if this is possible.
How can I do this?
I had a similar problem some time ago.
Watin can't do this directly but it exposes the mshtml objects needed to get some results.
At the time my code was pretty much like this:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WatiN.Core;
using WatiN.Core.Native.InternetExplorer;
using mshtml;
using System.Windows.Forms;
namespace ConsoleApplication1
{
class Program
{
[STAThread]
static void Main(string[] args)
{
Browser browser = new IE("http://www.google.com");
IEElement banner = browser.Images[0].NativeElement as IEElement;
IHTMLElement bannerHtmlElem = banner.AsHtmlElement;
IEElement bodyNative = browser.Body.NativeElement as IEElement;
mshtml.IHTMLElement2 bodyHtmlElem = (mshtml.IHTMLElement2)bodyNative.AsHtmlElement;
mshtml.IHTMLControlRange controlRange = (mshtml.IHTMLControlRange)bodyHtmlElem.createControlRange();
controlRange.add((mshtml.IHTMLControlElement)bannerHtmlElem);
controlRange.execCommand("Copy", false, System.Reflection.Missing.Value);
controlRange.remove(0);
if (Clipboard.GetDataObject() != null)
{
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Bitmap))
{
System.Drawing.Image image = (System.Drawing.Image)data.GetData(DataFormats.Bitmap, true);
// do something here
}
}
}
}
}
This little hack, basically, tries to copy the image to the clipboard. However I had a couple of problems making it work properly and ended up snapshoting the region around the image and saving it to disk.
Although this may not be very helpful it may point you in some directions..
I don't think you can get the binary information directly from WatiN. However you have Image.Uri method give you the URI of the image. So then it is easy to download it wih http request.
using (Browser browser = new IE("http://www.sp4ce.net/computer/2011/01/06/how-to-use-WatiN-with-NUnit.en.html"))
{
Image image = browser.Images[0];
Console.Write(image.Uri);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(image.Uri);
WebResponse response = request.GetResponse();
using (Stream stream = response.GetResponseStream())
using (FileStream fs = File.OpenWrite(#"c:\foo.png"))
{
byte[] bytes = new byte[1024];
int count;
while((count = stream.Read(bytes, 0, bytes.Length))!=0)
{
fs.Write(bytes, 0, count);
}
}
}
Hope this helps
A while ago I needed to extract image data too so I came with this solution:
Create an hidden field and a canvas inside the page using
ie.RunScript("document.body.innerHTML += \"<input type='hidden' id='hidden64'/>\";");
ie.RunScript("document.body.innerHTML += \"<canvas id='canv' width='150px' height='40px' ></canvas>\";");
transform it to base64 using javascript and retrieving its value
ie.RunScript("var c = document.getElementById('canv');");
ie.RunScript("var ctx = c.getContext('2d');");
ie.RunScript("var img = document.getElementsByName('imgCaptcha')[0];");
ie.RunScript("ctx.drawImage(img, 10, 10);");
ie.RunScript("document.getElementById('hidden64').value=c.toDataURL();");
then retrieving the codified value
string data = ie.Element(Find.ById("hidden64")).GetAttributeValue("value");
var base64Data = Regex.Match(data, #"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
var binData = Convert.FromBase64String(base64Data);
Bitmap im;
using (var stream = new MemoryStream(binData))
{
im = new Bitmap(stream);
}
Hope it helps :)
public Image GetImageFromElement(IHTMLElement Element)
{
int width = (int)Element.style.width;
int height = (int)Element.style.height;
IHTMLElementRender2 render = (IHTMLElementRender2)Element;
Bitmap screenCapture = new Bitmap(width, height);
Rectangle drawRectangle = new Rectangle(0, 0, width, height);
this.DrawToBitmap(screenCapture, drawRectangle);
Graphics graphics = Graphics.FromImage(screenCapture);
IntPtr graphicshdc = graphics.GetHdc();
render.DrawToDC(graphicshdc);
graphics.ReleaseHdc(graphicshdc);
graphics.Dispose();
return screenCapture as Image;
}
That's the Method i use for php generated images.
It's implimented in my own WebBrowserClass, which extends the webbrowser control.
(so "this" = WebBrowser)
But we have to import the IHTMLElementRender2 interface, to use the method.
[Guid("3050f669-98b5-11cf-bb82-00aa00bdce0b"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
ComVisible(true),
ComImport]
interface IHTMLElementRender2
{
void DrawToDC([In] IntPtr hDC);
void SetDocumentPrinter([In, MarshalAs(UnmanagedType.BStr)] string bstrPrinterName, [In] IntPtr hDC);
};
I found this method in web, about 1 year ago, so if you search for it you might find more information.
Iwan
I had such problem, and I could not solve it. PHP generated new images all the time so I used the CaptureWebPageToFile() method.

Categories