How do you retrieve a snapshot of a website in ASP.NET? - c#

Could anyone tell me how I could retrieve an image or a thumbnail of a website through my ASP.NET application? I have seen this functionality in a few sites such as Alexa etc.

Try SnapCasa's free and easy to use service. Just form your image tag like this:
<img src="http://SnapCasa.com/Get.aspx?code=[code]&size=[size]&url=[url]" />
Requires sign-up, but it's free for 500,000 requests a month. [code] is an api key that they provide after sign-up. [size] is one of three sizes available. [url] is the website address to the site for which you want to display a thumbnail.
If you want to work with the image from your code, here are a couple of helper methods:
static public byte[] GetBytesFromUrl(string url)
{
byte[] b;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(url);
WebResponse myResp = myReq.GetResponse();
Stream stream = myResp.GetResponseStream();
//int i;
using (BinaryReader br = new BinaryReader(stream))
{
//i = (int)(stream.Length);
b = br.ReadBytes(500000);
br.Close();
}
myResp.Close();
return b;
}
static public void WriteBytesToFile(string fileName, byte[] content)
{
FileStream fs = new FileStream(fileName, FileMode.Create);
BinaryWriter w = new BinaryWriter(fs);
try
{
w.Write(content);
}
finally
{
fs.Close();
w.Close();
}
}
Then, in your code, just use:
//get byte array for image
var imageBytes = GetBytesFromUrl("http://SnapCasa.com/Get.aspx?code=[code]&size=[size]&url=[url]");
//save file to disk
WriteBytesToFile("c:\someImageFile.jpg", imageBytes);

Should be doable using a web-browser object and saving the view port to a bitmap resized to thumbnail.
I have not tested this code but try tweaking it after substituting for the thumbnail params.
using (WebBrowser wb = new WebBrowser()) {
wb.ScrollBarsEnabled = false;
wb.AllowNavigation = true;
wb.ScriptErrorsSuppressed = true;
wb.ClientSize = new Size(thumbInfo_viewportWidth, thumbInfo_viewportHeight);
if ((thumbInfo_Uri != null)) {
wb.Navigate(thumbInfo_Uri.AbsoluteUri);
} else {
wb.Navigate("about:blank");
HtmlDocument doc = wb.Document.OpenNew(true);
doc.Write(thumbInfo_HTML);
wb.Refresh(WebBrowserRefreshOption.Completely);
}
// create an image of the client area of the webbrowser control, than
// scale it down to the dimensions specified.
if ((wb.Document != null && wb.Document.Body != null)) {
Rectangle rec = default(Rectangle);
rec.Size = wb.ClientSize;
using (Bitmap fullSizeBitmap = new Bitmap(thumbInfo_viewportWidth, thumbInfo_viewportHeight)) {
wb.DrawToBitmap(fullSizeBitmap, wb.Bounds);
using (Bitmap scaledBitmap = new Bitmap(thumbInfo_width, thumbInfo_height)) {
using (Graphics gr = Graphics.FromImage(scaledBitmap)) {
gr.SmoothingMode = Drawing2D.SmoothingMode.HighQuality;
gr.CompositingQuality = Drawing2D.CompositingQuality.HighQuality;
gr.InterpolationMode = Drawing2D.InterpolationMode.High;
Rectangle rect = new Rectangle(0, 0, thumbInfo_width, thumbInfo_height);
gr.DrawImage(fullSizeBitmap, rect, 0, 0, rec.Size.Width, rec.Size.Height, GraphicsUnit.Pixel);
scaledBitmap.Save(thumbInfo_physicalPath);
}
}
}
}
}
One thing to note that it is an expensive process.

Related

How to add multiple fpages to fixed document in xps?

My requirement is to create xps document which has 10 pages (say). I am using the following code to create a xps document. Please take a look.
// Create the new document
XpsDocument xd = new XpsDocument("D:\\9780545325653.xps", FileAccess.ReadWrite);
IXpsFixedDocumentSequenceWriter xdSW = xd.AddFixedDocumentSequence();
IXpsFixedDocumentWriter xdW = xdSW.AddFixedDocument();
IXpsFixedPageWriter xpW = xdW.AddFixedPage();
fontURI = AddFontResourceToFixedPage(xpW, #"D:\arial.ttf");
image = AddJpegImageResourceToFixedPage(xpW, #"D:\Single content\20_1.jpg");
StringBuilder pageContents = new StringBuilder();
pageContents.Append(ReadFile(#"D:\Single content\20.fpage\20.fpage", i));
xmlWriter = xpW.XmlWriter;
xmlWriter.WriteRaw(pageContents.ToString());
}
xmlWriter.Close();
xpW.Commit();
// Commit the fixed document
xdW.Commit();
// Commite the fixed document sequence writer
xdSW.Commit();
// Commit the XPS document itself
xd.Close();
}
private static string AddFontResourceToFixedPage(IXpsFixedPageWriter pageWriter, String fontFileName)
{
string fontUri = "";
using (XpsFont font = pageWriter.AddFont(false))
{
using (Stream dstFontStream = font.GetStream())
using (Stream srcFontStream = File.OpenRead(fontFileName))
{
CopyStream(srcFontStream, dstFontStream);
// commit font resource to the package file
font.Commit();
}
fontUri = font.Uri.ToString();
}
return fontUri;
}
private static Int32 CopyStream(Stream srcStream, Stream dstStream)
{
const int size = 64 * 1024; // copy using 64K buffers
byte[] localBuffer = new byte[size];
int bytesRead;
Int32 bytesMoved = 0;
// reset stream pointers
srcStream.Seek(0, SeekOrigin.Begin);
dstStream.Seek(0, SeekOrigin.Begin);
// stream position is advanced automatically by stream object
while ((bytesRead = srcStream.Read(localBuffer, 0, size)) > 0)
{
dstStream.Write(localBuffer, 0, bytesRead);
bytesMoved += bytesRead;
}
return bytesMoved;
}
private static string ReadFile(string filePath,int i)
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite);
StringBuilder sb = new StringBuilder();
using (StreamReader sr = new StreamReader(fs))
{
String line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
sb.AppendLine(line);
}
}
string allines = sb.ToString();
//allines = allines.Replace("FontUri=\"/Resources/f7728e4c-2606-4fcb-b963-d2d3f52b013b.odttf\"", "FontUri=\"" + fontURI + "\" ");
//XmlReader xmlReader = XmlReader.Create(fs, new XmlReaderSettings() { IgnoreComments = true });
XMLSerializer serializer = new XMLSerializer();
FixedPage fp = (FixedPage)serializer.DeSerialize(allines, typeof(FixedPage));
foreach (Glyphs glyph in fp.lstGlyphs)
{
glyph.FontUri = fontURI;
}
fp.Path.PathFill.ImageBrush.ImageSource = image;
fs.Close();
string fpageString = serializer.Serialize(fp);
return fpageString;
}
private static string AddJpegImageResourceToFixedPage(IXpsFixedPageWriter pageWriter, String imgFileName)
{
XpsImage image = pageWriter.AddImage("image/jpeg");
using (Stream dstImageStream = image.GetStream())
using (Stream srcImageStream = File.OpenRead(imgFileName))
{
CopyStream(srcImageStream, dstImageStream); // commit image resource to the package file
//image.Commit();
}
return image.Uri.ToString();
}
If you see it, i would have passed single image and single fpage to create a xps document. I want to pass multiple fpages list and image list to create a xps document which has multiple pages..?
You are doing this in the most excruciatingly difficult manner possible. I'd suggest taking the lazy man's route.
Realize that an XpsDocument is just a wrapper on a FixedDocumentSequence, which contains zero or more FixedDocuments, which contains zero or more FixedPages. All these types can be created, manipulated and combined without writing XML.
All you really need to do is create a FixedPage with whatever content on it you need. Here's an example:
static FixedPage CreateFixedPage(Uri imageSource)
{
FixedPage fp = new FixedPage();
fp.Width = 320;
fp.Height = 240;
Grid g = new Grid();
g.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;
g.VerticalAlignment = System.Windows.VerticalAlignment.Center;
fp.Children.Add(g);
Image img = new Image
{
UriSource = imageSource,
};
g.Children.Add(image);
return fp;
}
This is all WPF. I'm creating a FixedPage that has as its root a Grid, which contains an Image that is loaded from the given Uri. The image will be stretched to fill the available space of the Grid. Or, you could do whatever you want. Create a template as a UserControl, send it text to place within itself, whatever.
Next, you just need to add a bunch of fixed pages to an XpsDocument. It's incredibly hard, so read carefully:
public void WriteAllPages(XpsDocument document, IEnumerable<FixedPage> pages)
{
var writer = XpsDocument.CreateXpsDocumentWriter(document);
foreach(var page in pages)
writer.Write(page);
}
And that's all you need to do. Create your pages, add them to your document. Done.

Post image from Windows Phone Application to PHP

I am trying to develop an application for Windows Phone 7 which uploads a selected picture (from the picture chooser task) to a server with the use of PHP.
I am trying to use HttpWebRequest in order to do this. And the data is posted successfully too.
The Problem that I am facing is that the image is required to be encoded to base64 before posting.
And, I am not able to encode it properly.
This is my C# code so far:
public partial class SamplePage : PhoneApplicationPage
{
public SamplePage()
{
InitializeComponent();
}
PhotoChooserTask selectphoto = null;
private void SampleBtn_Click(object sender, RoutedEventArgs e)
{
selectphoto = new PhotoChooserTask();
selectphoto.Completed += new EventHandler<PhotoResult>(selectphoto_Completed);
selectphoto.Show();
}
void selectphoto_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
BinaryReader reader = new BinaryReader(e.ChosenPhoto);
image1.Source = new BitmapImage(new Uri(e.OriginalFileName));
txtBX.Text = e.OriginalFileName;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://"+QR_Reader.MainPage.txtBlck+"/beamer/saveimage.php");
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
string str = BitmapToByte(image1);
MessageBox.Show(str);
string postData = String.Format("image={0}", str);
// Getting the request stream.
request.BeginGetRequestStream
(result =>
{
// Sending the request.
using (var requestStream = request.EndGetRequestStream(result))
{
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(postData);
writer.Flush();
}
}
// Getting the response.
request.BeginGetResponse(responseResult =>
{
var webResponse = request.EndGetResponse(responseResult);
using (var responseStream = webResponse.GetResponseStream())
{
using (var streamReader = new StreamReader(responseStream))
{
string srresult = streamReader.ReadToEnd();
}
}
}, null);
}, null);
} // end of taskresult == OK
} // end of select photo completed
private Stream ImageToStream(Image image1)
{
WriteableBitmap wb = new WriteableBitmap(400, 400);
wb.Render(image1, new TranslateTransform { X = 400, Y = 400 });
wb.Invalidate();
Stream myStream = new MemoryStream();
wb.SaveJpeg(myStream, 400, 400, 0, 70);
return myStream;
}
private string BitmapToByte(Image image) //I suspect there is something wrong here
{
Stream photoStream = ImageToStream(image);
BitmapImage bimg = new BitmapImage();
bimg.SetSource(photoStream); //photoStream is a stream containing data for a photo
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
WriteableBitmap wbitmp = new WriteableBitmap(bimg);
wbitmp.SaveJpeg(ms, wbitmp.PixelWidth, wbitmp.PixelHeight, 0, 100);
bytearray = ms.ToArray();
}
string str = Convert.ToBase64String(bytearray);
return str;
}
}
The BitmapToByte function is used to convert the image to base64 string.
And, the ImageToStream function is used to convert it to stream.
Now, I seriously suspect that there is something wrong in these two functions.
Further, I'm getting exactly the same base64 string for every image. Yes, I'm getting exactly same base64 string irrespective of what image I'm selecting. This is very weird.
I don't know what is wrong with this.
I've uploaded a text file here: http://textuploader.com/?p=6&id=vWZy
It contains that base64 string.
On, the server side, the PHP is accepting the postdata successfully and the decoding is working perfectly too (I decoded some base64 strings manually to ensure this).
Only problem I'm facing is base64 encoding.
Please help me.
EDIT
I've made the following changes in the ImageToStream and BitmapToByte functions:
private MemoryStream ImageToStream(Image image1)
{
WriteableBitmap wb = new WriteableBitmap(400, 400);
wb.Render(image1, new TranslateTransform { X = 400, Y = 400 });
wb.Invalidate();
MemoryStream myStream = new MemoryStream();
wb.SaveJpeg(myStream, 400, 400, 0, 70);
return myStream;
}
private string BitmapToByte(Image image)
{
MemoryStream photoStream = ImageToStream(image);
byte[] bytearray = photoStream.ToArray();
string str = Convert.ToBase64String(bytearray);
return str;
}
You BitmapToByte method is tremendously overcomplicated. Change ImageToStream to return a MemoryStream and:
private string BitmapToByte(Image image)
{
MemoryStream photoStream = ImageToStream(image);
byte[] bytearray = photoStream.ToArray();
string str = Convert.ToBase64String(bytearray);
return str;
}

Image Resizing from SQL Database on the fly with MVC2

I have a simple MVC2 app that uploads a file from the browser to an MS SQL database as an Image blob.
Then I can return the results with something like:
public FileContentResult ShowPhoto(int id)
{
TemporaryImageUpload tempImageUpload = new TemporaryImageUpload();
tempImageUpload = _service.GetImageData(id) ?? null;
if (tempImageUpload != null)
{
byte[] byteArray = tempImageUpload.TempImageData;
return new FileContentResult (temp, "image/jpeg");
}
return null;
}
But I want to return these images resized as both thumbnails and as a gallery-sized view. Is this possible to do within this Result? I've been playing around with the great imageresizer.net but it seems to want to store the images on my server which I want to avoid. Is it possible to do this on the fly..?
I need to keep the original file and don't, if possible, want to store the images as files on the server.
Thanks for any pointers!
ImageResizer.NET allows you to pass a stream to it for resizing, see Managed API usage
The method you'd use is:
ImageResizer.ImageBuilder.Current.Build(object source, object dest, ResizeSettings settings)
I modified your method to go about it this way, but it is untested. Hope it helps.
public FileContentResult ShowPhoto(int id)
{
TemporaryImageUpload tempImageUpload = new TemporaryImageUpload();
tempImageUpload = _service.GetImageData(id) ?? null;
if (tempImageUpload != null)
{
byte[] byteArray = tempImageUpload.TempImageData;
using(var outStream = new MemoryStream()){
using(var inStream = new MemoryStream(byteArray)){
var settings = new ResizeSettings("maxwidth=200&maxheight=200");
ImageResizer.ImageBuilder.Current.Build(inStream, outStream, settings);
var outBytes = outStream.ToArray();
return new FileContentResult (outBytes, "image/jpeg");
}
}
}
return null;
}
There was a recent Hanselminutes podcast on Image Resizing with Nathanael Jones discussing some of the pitfalls of image resizing.
Even if you do not have 30 odd minutes to listen to the full podcast, the show notes point to some interesting resizing pitfalls, as well as an image resizing library also written by Nathanael Jones.
You could resize the image on the fly:
public void ResizeImage(Stream input, Stream output, int newWidth, int maxHeight)
{
using (var srcImage = Image.FromStream(input))
{
int newHeight = srcImage.Height * newWidth / srcImage.Width;
if (newHeight > maxHeight)
{
newWidth = srcImage.Width * maxHeight / srcImage.Height;
newHeight = maxHeight;
}
using (var newImage = new Bitmap(newWidth, newHeight))
using (var gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight));
newImage.Save(output, ImageFormat.Jpeg);
}
}
}
and then you could have 2 controller actions (one that displays the full image size and one that displays a thumbnail):
public ActionResult Thumbnail(int id)
{
var tempImageUpload = new TemporaryImageUpload();
tempImageUpload = _service.GetImageData(id) ?? null;
if (tempImageUpload == null)
{
return HttpNotFound();
}
using (var input = new MemoryStream(tempImageUpload.TempImageData))
using (var output = new MemoryStream())
{
ResizeImage(input, output, 640, 1000);
return File(output.ToArray(), "image/jpeg");
}
}

Retrieving favicon as icon instead of image

I used the favicon-code I found here to retrieve the favicon of the site loaded in the browser element.
I want to use this favicon as the icon of my Windows Form.
Thanks to JP Hellemons this code works:
private void browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
this.Icon = favicon(GetActiveBrowser().Url);
}
private WebBrowser GetActiveBrowser() {
return (WebBrowser)tabs.SelectedTab.Controls[0];
}
private Icon favicon(Uri url) {
WebRequest request = (HttpWebRequest)WebRequest.Create("http://" + url.Host + "/favicon.ico");
Bitmap bm = new Bitmap(32, 32);
MemoryStream memStream;
using (Stream response = request.GetResponse().GetResponseStream()) {
memStream = new MemoryStream();
byte[] buffer = new byte[1024];
int byteCount;
do {
byteCount = response.Read(buffer, 0, buffer.Length);
memStream.Write(buffer, 0, byteCount);
} while (byteCount > 0);
}
bm = new Bitmap(Image.FromStream(memStream));
if (bm != null) {
Icon ic = Icon.FromHandle(bm.GetHicon());
return ic;
} else
return Properties.Resources.GZbrowser;
}
According to this documentation, it should work from stream.
http://msdn.microsoft.com/en-us/library/system.drawing.icon.aspx
I used this article: http://odetocode.com/Blogs/scott/archive/2004/10/05/webrequest-and-binary-data.aspx
WebRequest request = (HttpWebRequest)WebRequest.Create("http://" + url.Host + "/favicon.ico");
Icon ic = new Icon(); // put default here
Bitmap bm = new Bitmap();
try
{
using(WebResponse response = request.GetResponse())
{
using(Stream responseStream = response.GetResponseStream())
{
using(MemoryStream ms = new MemoryStream())
{
var tmp = Image.FromStream(ms); // changed bitmap to image
bm = new Bitmap(tmp);
}
}
}
}catch{}
if(bm != null)
{
ic = Icon.FromHandle(bm.GetHicon);
}
return ic;
Edit: something like this should do it
Edit2: changed some things in the answer. Can you try this?
Final edit: (lol)
Just tested this in a windows form app and this works! :)
Uri url = new Uri("http://www.google.nl");
WebRequest request = (HttpWebRequest)WebRequest.Create("http://" + url.Host + "/favicon.ico");
Bitmap bm = new Bitmap(32,32);
MemoryStream memStream;
using (Stream response = request.GetResponse().GetResponseStream())
{
memStream = new MemoryStream();
byte[] buffer = new byte[1024];
int byteCount;
do
{
byteCount = response.Read(buffer, 0, buffer.Length);
memStream.Write(buffer, 0, byteCount);
} while (byteCount > 0);
}
bm = new Bitmap(Image.FromStream(memStream));
if (bm != null)
{
Icon ic = Icon.FromHandle(bm.GetHicon());
this.Icon = ic;
}
Read response byte array first, than create MemoryStream of it and create icon from that MemoryStream.
Network stream do not support seek operations that seem to be necessary for creating an icon.

How do I create a thumbnail from an image using C# Win Mobile 6.5/Compact framework?

I am trying to make/use a smaller image than the one taken with the camera to display in parts of my program (due to memory issues...)
Unfortunately I don't seem to be able to find ways to make a smaller image/thumbnail on the mobile device - the way it is possible in normal windows...
Is there a way to make a smaller image on Win Mobile 6.5/Compact Framework?
For example - these do not work on Win Mobile
What is the "best" way to create a thumbnail using ASP.NET?
This looks promising - but i want to just put the image on a PictureBox - and not sure how to use this to make it work.
This code should be work. I have also implemented this code. For that I have used OpenNETCF.Drawing.dll.
barray = GetImage(filepath);
if (barray != null)
{
ms.Write(barray, 0, barray.Length - 1);
imageBitmap = CreateThumbnail(ms, new Size(PreviewImageWidth, PreviewImageHeight));
bm = ImageUtils.IBitmapImageToBitmap(imageBitmap);
// m_CurrentImageID = Convert.ToInt32(lstPic.ToList()[index].Id);
PictureBox ib = ((PictureBox)this.imagePanel.Controls[(nIndex * 2) + 1]);
ib.Image = bm;
}
private byte[] GetImage(string FilePath)
{
byte[] barray;
if (File.Exists(FilePath))
{
FileInfo _fileInfo = new FileInfo(FilePath);
long _NumBytes = _fileInfo.Length;
FileStream _FStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read);
BinaryReader _BinaryReader = new BinaryReader(_FStream);
barray = _BinaryReader.ReadBytes(Convert.ToInt32(_NumBytes));
_FStream.Flush();
_FStream.Dispose();
return barray;
}
else
{
return null;
}
}
public IBitmapImage CreateThumbnail(Stream stream, Size size)
{
IBitmapImage imageBitmap;
ImageInfo ii;
IImage image;
ImagingFactory factory = new ImagingFactoryClass();
try
{
factory.CreateImageFromStream(new StreamOnFile(stream), out image);
image.GetImageInfo(out ii);
factory.CreateBitmapFromImage(image, (uint)size.Width, (uint)size.Height, ii.PixelFormat, InterpolationHint.InterpolationHintDefault, out imageBitmap);
return imageBitmap;
}
catch (Exception ex)
{
CreateLogFiles Err = new CreateLogFiles();
Err.ErrorLog(ex.Message);
return null;
}
finally
{
imageBitmap = null;
image = null;
factory = null;
}
}
This should work:
this.pictureBox1.Image = System.Drawing.Image.FromFile(#"\path to image").GetThumbnailImage(100, 100, null, IntPtr.Zero);
but the quality of thumbnail may not be as good. For quality thumbnail images you could refer to this post here

Categories