Set Secondary Tile BackgroundImage from Image in Isolated Storage - c#

This is how I get the stream from an image url:
using (var httpClient = new HttpClient())
{
response = await httpClient.GetStreamAsync(new Uri(IMAGEURL_HERE, UriKind.Absolute));
}
SaveImage(response);
And this is how I save it to IsoloatedStorage:
private void SaveImage(Stream result)
{
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(result);
var wb = new WriteableBitmap(bitmap);
using (IsolatedStorageFileStream fileStream = file.CreateFile("FILENAME.jpg"))
{
int width = wb.PixelWidth;
int height = wb.PixelHeight;
if (wb.PixelWidth > 336)
{
width = 336;
}
if (wb.PixelHeight > 336)
{
height = 336;
}
Extensions.SaveJpeg(wb, fileStream, width, height, 0, 100);
}
}
}
So let's say the file is FILENAME.jpg, I thought I could set it as BackgroundImage to a Secondary Tile like this:
var tileData = new FlipTileData()
{
...
BackgroundImage = new Uri("isostore:/Shared/ShellContent/FILENAME.jpg", UriKind.Absolute),
...
It won't work. It throws no exception, only the image won't be displayed. What do I miss? Of course if I put the Image Url as Uri to BackgroundImage it works, but this is not what I want.
Edit: And I have seen similar questions here but it did not help me with my code.

Try this. May be its help.
string imageFolder = #"\Shared\ShellContent";
string shareJPEG = "FILENAME.jpg";
private void SaveImage(Stream result)
{
using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
{
if(!myIsolatedStorage.DirectoryExists(imageFolder))
{
myIsolatedStorage.CreateDirectory(imageFolder);
}
if (myIsolatedStorage.FileExists(shareJPEG))
{
myIsolatedStorage.DeleteFile(shareJPEG);
}
string filePath = System.IO.Path.Combine(imageFolder, shareJPEG);
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(filePath);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(result);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
int width = wb.PixelWidth;
int height = wb.PixelHeight;
if (wb.PixelWidth > 336)
{
width = 336;
}
if (wb.PixelHeight > 336)
{
height = 336;
}
Extensions.SaveJpeg(wb, fileStream, width, height, 0, 100);
fileStream.Close();
}
}
private void CreateTile()
{
var tileData = new FlipTileData()
{
....
string filePath = System.IO.Path.Combine(imageFolder, shareJPEG);
BackgroundImage = new Uri(#"isostore:" + filePath, UriKind.Absolute);
....
}
}

Related

Resize Image When Upload in Asp Core

I need to change the size of the photo and save it to a new size when the user selects a photo for the upload, before saving the photo.
i using this code but it not save with new size . whats the problem ?
public async Task<IActionResult> UploadNewsPic()
{
var file = Request.Form.Files[0];
try
{
if (file.Length > 0)
{
string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
string fullPath = Path.Combine(_applicationRoot.UploadNewPath(), file.Name);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
if (file.IsImage())
{
await file.ResizeImage(3, 3);
file.CopyTo(stream);
}
}
}
return Ok();
}
catch (Exception e)
{
return BadRequest();
}
}
and this is Resize Extention :
public async static Task<Image> ResizeImage(this IFormFile file, int width, int height)
{
using (var memoryStream = new MemoryStream())
{
await file.CopyToAsync(memoryStream);
using (var img = Image.FromStream(memoryStream))
{
return img.Resize(width, height);
}
}
}
public static Image Resize(this Image image, int width, int height)
{
var res = new Bitmap(width, height);
using (var graphic = Graphics.FromImage(res))
{
graphic.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphic.SmoothingMode = SmoothingMode.HighQuality;
graphic.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphic.CompositingQuality = CompositingQuality.HighQuality;
graphic.DrawImage(image, 0, 0, width, height);
}
return res;
}
You need to save the result from ResizeImage to the stream. Right now you are just copying the original file.
var img = await file.ResizeImage(3, 3);
img.Save(stream, SomeFormat);
Your ResizeImage() function return a resized image, it doesn't edit the image itself, so you must set it to a variable.
if (file.IsImage())
{
Image imageResized = await file.ResizeImage(3, 3);
// ...
}

How to download an image URL to switch to byte [] up and read it WP8 C#

for (int i = 3; i < 10; i++)
{
Uri uriimg = new Uri("http://i.msdn.microsoft.com/dynimg/IC53593" + i + ".jpg", UriKind.RelativeOrAbsolute);
SaveToLocalStorage(ImageToArray(uriimg), "anh1.jpg");
}
private byte[] ImagesToArray(Uri uriimg)
{
var image = new BitmapImage(uriimg);
MemoryStream ms = new MemoryStream();
image.ImageOpened += (s, e) =>
{
image.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(image);
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
};
return ms.ToArray();
}
public async void SaveToLocalStorage(byte[] _imageBytes, string fileName)
{
if (_imageBytes == null)
{
return;
}
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
if (!isoFile.DirectoryExists("dataImages"))
{
isoFile.CreateDirectory("dataImages");
}
string filePath = System.IO.Path.Combine("dataImages", fileName);
using (var stream = isoFile.CreateFile(filePath))
{
await stream.WriteAsync(_imageBytes, 0, _imageBytes.Length);
}
}
public ImageSource LoadFromLocalStorage(string fileName)
{
var isoFile = IsolatedStorageFile.GetUserStoreForApplication();
ImageSource imageSource = null;
if (isoFile.DirectoryExists("dataImages"))
{
string filePath = System.IO.Path.Combine("dataImages", fileName);
using (var imageStream = isoFile.OpenFile(filePath, FileMode.Open, FileAccess.Read))
{
imageSource = PictureDecoder.DecodeJpeg(imageStream);
}
}
return imageSource;
}
I get the value as byte [0] it can not convert to byte [].
The problem I see is in ImagesToArray. You create a new MemoryStream, subscribe to an event that sets it, and then immediately return it. I'm pretty sure that ms will have 0 bytes when it is returned.
You should instead not use image.ImageOpened, and just put that code in the ImagesToArray method directly:
private byte[] ImagesToArray(Uri uriimg)
{
var image = new BitmapImage(uriimg);
MemoryStream ms = new MemoryStream();
image.CreateOptions = BitmapCreateOptions.None;
WriteableBitmap wb = new WriteableBitmap(image);
wb.SaveJpeg(ms, image.PixelWidth, image.PixelHeight, 0, 100);
return ms.ToArray();
}

Store and retrieve binary image in WPF

I have saved Image in database as binary :
Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
if (fd.ShowDialog() == true)
{
ILogo.Source = new BitmapImage(new Uri(fd.FileName));
Stream stream = File.OpenRead(fd.FileName);
binaryImage = new byte[stream.Length];
stream.Read(binaryImage, 0, (int)stream.Length);
}
_merchantInfo.Logo = binaryImage;
I want to read the image and showing it image tool, I tried this:
_merchantInfo = new MerchantInfo();
_merchantInfo = _context.MerchantInfo.FirstOrDefault();
byte[] binaryPhoto = (byte[])_merchantInfo.Logo;
Stream stream = new MemoryStream(binaryPhoto);
_merchantLogo = new BitmapImage();
_merchantLogo.StreamSource = stream;
ILogo.Source = _merchantLogo;
No Error, But the image does not showing in image box :(
Is there error in my code?
Thanks.
Universal Binary Storage Method -> You must read all the bites of the picture/file and save them in a binary array.
OpenFileDialog FileDialog = new OpenFileDialog();
byte[] BinaryData = new byte[]{};
if(FileDialog.ShowDialog())
{
BinaryData = System.IO.File.ReadAllBytes(FileDialog.FileName);
}
Binary Retrieval(For Images Only in WPF) -> You must set an BitmapImage and store all the binary information within it with the help of a MemoryStream.
BitmapImage image = new BitmapImage();
byte[] binary = new byte{}; /* <--- The array where
we stored the binary
information of the picture*/
image.BeginInit();
image.StreamSource = new System.IO.MemoryStream(binary)
image.EndInit();
Universal Binary Retrieval and Binary File Upload Method ->
byte[] BinaryData = new byte[]{};
private void Download()
{
OpenFileDialog FileDialog = new OpenFileDialog();
if(FileDialog.ShowDialog())
{
BinaryData = System.IO.File.ReadAllBytes(FileDialog.FileName);
}
}
private void Save()
{
OpenFileDialog FileDialog = new SaveFileDialog();
if(FileDialog.ShowDialog())
{
using(System.IO.Stream stream = new File.Open(FileDialog.FileName, FileMode.Create))
{
using (var BinaryWriter = new BinaryWriter(stream))
{
BinaryWriter.Write(BinaryData);
BinaryWriter.Close();
}
}
}
}
Finally I have solved this, here is the code for store and retrieve the image in database as binary :
To store the image:
Microsoft.Win32.OpenFileDialog fd = new Microsoft.Win32.OpenFileDialog();
if (fd.ShowDialog() == true)
{
ILogo.Source = new BitmapImage(new Uri(fd.FileName));
Stream stream = File.OpenRead(fd.FileName);
binaryImage = new byte[stream.Length];
stream.Read(binaryImage, 0, (int)stream.Length);
}
_merchantInfo.Logo = binaryImage;
_context.SaveChanges();
Image retrieval and display:
merchantInfo = new MerchantInfo();
_merchantInfo = _context.MerchantInfo.FirstOrDefault();
byte[] binaryPhoto = (byte[])_merchantInfo.Logo;
Stream stream = new MemoryStream(binaryPhoto);
_merchantLogo = new BitmapImage();
_merchantLogo.BeginInit();
_merchantLogo.StreamSource = stream;
_merchantLogo.EndInit();
ILogo.Source = _merchantLogo;
Thanks for everyone helped me :)
i create this class and i am using it without any problems, try it and share it.
/// <summary>
/// created by Henka Programmer.
/// Class to make the converting images formats and data structs so easy.
/// This Class supporte the following types:
/// - BtimapImage,
/// - Stream,
/// - ByteImage
///
/// and the other option is image resizing.
/// </summary>
public class Photo
{
public BitmapImage BitmapImage;
public System.IO.Stream Stream;
public byte[] ByteImage;
public Photo(Uri PhotoUri)
{
this.BitmapImage = new BitmapImage(PhotoUri);
this.Stream = new MemoryStream();
this.Stream = this.BitmapImage.StreamSource;
this.ByteImage = StreamToByteArray(this.Stream);
}
public Photo(Bitmap Photo_Bitmap)
: this((ImageSource)(new ImageSourceConverter().ConvertFrom(Photo_Bitmap)))
{
/*
ImageSourceConverter c = new ImageSourceConverter();
byte[] bytes = (byte[])TypeDescriptor.GetConverter(Photo_Bitmap).ConvertTo(Photo_Bitmap, typeof(byte[]));
Photo ph = new Photo(bytes);*/
}
public Photo(ImageSource PhotoSource) : this(PhotoSource as BitmapImage) { }
public Photo(BitmapImage BitmapPhoto)
{
this.BitmapImage = BitmapPhoto;
this.ByteImage = GetByteArrayFromImageControl(BitmapPhoto);
this.Stream = new MemoryStream();
WriteToStream(this.Stream, this.ByteImage);
}
public Photo(string path)
{
try
{
this.Stream = System.IO.File.Open(path, System.IO.FileMode.Open);
this.BitmapImage = new BitmapImage();
BitmapImage.BeginInit();
BitmapImage.StreamSource = Stream;
BitmapImage.EndInit();
this.ByteImage = StreamToByteArray(this.Stream);
}
catch (Exception exception)
{
Debug.WriteLine(exception.Message);
}
}
public Photo(byte[] byteimage)
{
this.ByteImage = new byte[byteimage.Length];
this.ByteImage = byteimage;
// WriteToStream(this.Stream, this.ByteImage);
//MemoryStream ms = new MemoryStream(byteimage);
this.Stream = new MemoryStream(byteimage);
}
private void WriteToStream(Stream s, Byte[] bytes)
{
using (var writer = new BinaryWriter(s))
{
writer.Write(bytes);
}
}
private byte[] StreamToByteArray(Stream inputStream)
{
if (!inputStream.CanRead)
{
throw new ArgumentException();
}
// This is optional
if (inputStream.CanSeek)
{
inputStream.Seek(0, SeekOrigin.Begin);
}
byte[] output = new byte[inputStream.Length];
int bytesRead = inputStream.Read(output, 0, output.Length);
Debug.Assert(bytesRead == output.Length, "Bytes read from stream matches stream length");
return output;
}
private BitmapImage BitmapImageFromBytes(byte[] bytes)
{
BitmapImage image = new BitmapImage();
using (System.IO.MemoryStream imageStream = new System.IO.MemoryStream())
{
imageStream.Write(ByteImage, 0, ByteImage.Length);
imageStream.Seek(0, System.IO.SeekOrigin.Begin);
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.StreamSource = imageStream;
image.EndInit();
//image.Freeze();
}
return image;
}
public BitmapImage GetResizedBitmap(int width, int height)
{
ImageSource imgSrc = CreateResizedImage(this.ByteImage, width, height);
return new Photo(GetEncodedImageData(imgSrc, ".jpg")).BitmapImage;
}
private ImageSource CreateResizedImage(byte[] imageData, int width, int height)
{
BitmapImage bmpImage = new BitmapImage();
bmpImage.BeginInit();
if (width > 0)
{
bmpImage.DecodePixelWidth = width;
}
if (height > 0)
{
bmpImage.DecodePixelHeight = height;
}
bmpImage.StreamSource = new MemoryStream(imageData);
bmpImage.CreateOptions = BitmapCreateOptions.None;
bmpImage.CacheOption = BitmapCacheOption.OnLoad;
bmpImage.EndInit();
Rect rect = new Rect(0, 0, width, height);
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
drawingContext.DrawImage(bmpImage, rect);
}
RenderTargetBitmap resizedImage = new RenderTargetBitmap(
(int)rect.Width, (int)rect.Height, // Resized dimensions
96, 96, // Default DPI values
PixelFormats.Default); // Default pixel format
resizedImage.Render(drawingVisual);
return resizedImage;
}
internal byte[] GetEncodedImageData(ImageSource image, string preferredFormat)
{
byte[] returnData = null;
BitmapEncoder encoder = null;
switch (preferredFormat.ToLower())
{
case ".jpg":
case ".jpeg":
encoder = new JpegBitmapEncoder();
break;
case ".bmp":
encoder = new BmpBitmapEncoder();
break;
case ".png":
encoder = new PngBitmapEncoder();
break;
case ".tif":
case ".tiff":
encoder = new TiffBitmapEncoder();
break;
case ".gif":
encoder = new GifBitmapEncoder();
break;
case ".wmp":
encoder = new WmpBitmapEncoder();
break;
}
if (image is BitmapSource)
{
MemoryStream stream = new MemoryStream();
encoder.Frames.Add(BitmapFrame.Create(image as BitmapSource));
encoder.Save(stream);
stream.Seek(0, SeekOrigin.Begin);
returnData = new byte[stream.Length];
BinaryReader br = new BinaryReader(stream);
br.Read(returnData, 0, (int)stream.Length);
br.Close();
stream.Close();
}
return returnData;
}
public byte[] GetByteArrayFromImageControl(BitmapImage imageC)
{
MemoryStream memStream = new MemoryStream();
JpegBitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(imageC));
encoder.Save(memStream);
return memStream.GetBuffer();
}
public ImageSource ToImageSource()
{
ImageSource imgSrc = this.BitmapImage as ImageSource;
return imgSrc;
}
public System.Windows.Controls.Image ToImage()
{
System.Windows.Controls.Image Img = new System.Windows.Controls.Image();
Img.Source = this.ToImageSource();
return Img;
}
}

How to save a picture from PhotoChooserTask

I would like to save a photo selected with the PhotoChooserTask, but I am unsure of the proper method. So far, I have implemented the PhotoChooserTask_Completed method, but what is the proper method to save this to a bitmap?
EDIT: added basic implementation. The goal is to update a hubtile image to an image that the user selects from the PhotoChooserTask.
Note: I have placed the Settings class and TileItem class at the bottom for quick reference.
MainPage.xaml
string shareJPEG = "shareImage.jpg";
string linkJPEG = "linkImage.jpg";
BitmapImage shareImg;
BitmapImage linkImg;
public MainPage()
{
InitializeComponent();
CreateHubTiles();
photoChooserTask = new PhotoChooserTask();
photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
}
public void CreateHubTiles()
{
if (Settings.shareImageUpdated.Value == true)
{
//Settings.shareImage.Value = new BitmapImage();
shareImg = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(shareJPEG, FileMode.Open, FileAccess.Read))
{
//Settings.shareImage.Value.SetSource(fileStream);
shareImg.SetSource(fileStream);
//this.img.Height = bi.PixelHeight;
//this.img.Width = bi.PixelWidth;
}
}
//this.img.Source = bi;
}
else
{
//Settings.shareImage.Value = new BitmapImage(new Uri("/Images/shareStatusImage.jpg", UriKind.Relative));
shareImg = new BitmapImage(new Uri("/Images/shareStatusImage.jpg", UriKind.Relative));
}
if (Settings.linkImageUpdated.Value == true)
{
//Settings.linkImage.Value = new BitmapImage();
linkImg = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(linkJPEG, FileMode.Open, FileAccess.Read))
{
//Settings.linkImage.Value.SetSource(fileStream);
linkImg.SetSource(fileStream);
//this.img.Height = bi.PixelHeight;
//this.img.Width = bi.PixelWidth;
}
}
//this.img.Source = bi;
}
else
{
//Settings.linkImage.Value = new BitmapImage(new Uri("/Images/shareStatusImage.jpg", UriKind.Relative));
linkImg = new BitmapImage(new Uri("/Images/shareLinkImage.jpg", UriKind.Relative));
}
List<TileItem> tileItems = new List<TileItem>()
{
//new TileItem() { ImageUri = Settings.shareImage.Value, Title = "status", /*Notification = "last shared link uri",*/ Message = Settings.statusMessage.Value, GroupTag = "TileGroup", TileName = AppResource.Main_MainPage_HubTile_Status_Title },
new TileItem() { ImageUri = shareImg, Title = "status", /*Notification = "last shared link uri",*/ Message = Settings.statusMessage.Value, GroupTag = "TileGroup", TileName = AppResource.Main_MainPage_HubTile_Status_Title },
//new TileItem() { ImageUri = Settings.linkImage.Value, Title = "link", /*Notification = "last shared status message",*/ Message = Settings.linkUri.Value, GroupTag = "TileGroup", TileName = AppResource.Main_MainPage_HubTile_Link_Title },
new TileItem() { ImageUri = linkImg, Title = "link", /*Notification = "last shared status message",*/ Message = Settings.linkUri.Value, GroupTag = "TileGroup", TileName = AppResource.Main_MainPage_HubTile_Link_Title },
};
this.tileList.ItemsSource = tileItems;
}
public void changePictureMenuItem_Tap(object sender, System.Windows.Input.GestureEventArgs e)
{
var menuItem = (MenuItem)sender;
tileItem = menuItem.DataContext as TileItem; //for PhotoChooserTask_Completed
try
{
photoChooserTask.Show();
}
catch (System.InvalidOperationException ex)
{
//MessageBox.Show("An error occurred");
MessageBox.Show(AppResource.Main_MainPage_ContextMenu_ChangePicture_Error_Message);
}
}
void photoChooserTask_Completed(object sender, PhotoResult e)
{
//Debug.WriteLine("***\t In photoChooserTask_Completed function of ChoosePhotoPage\t ***");
if (e.TaskResult == TaskResult.OK)
{
//get the correct hubtile that was clicked and set image source to respective hubtile
string tileTitle = tileItem.Title.ToString();
switch (tileTitle)
{
case "status":
tileItem.ImageUri.SetSource(e.ChosenPhoto); //sets the tile image immediately, but does not persist when the MainPage is navigated away
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(shareJPEG))
{
myIsolatedStorage.DeleteFile(shareJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(shareJPEG);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
Settings.shareImageUpdated.Value = true; //simple boolean value that exists in isolated storage
break;
case "link":
tileItem.ImageUri.SetSource(e.ChosenPhoto); //sets the tile image immediately, but does not persist when the MainPage is navigated away
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(linkJPEG))
{
myIsolatedStorage.DeleteFile(linkJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(linkJPEG);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
Settings.linkImageUpdated.Value = true;
break;
}
}
The Settings and TileItem classes:
Settings.cs (uses key/value pairs to store data in isolated storage)
public static readonly Setting<BitmapImage> shareImage = new Setting<BitmapImage>("shareImage", new BitmapImage(new Uri("/Images/shareStatusImage.jpg", UriKind.Relative)));
public static readonly Setting<BitmapImage> linkImage = new Setting<BitmapImage>("linkImage", new BitmapImage(new Uri("/Images/shareLinkImage.jpg", UriKind.Relative)));
public static readonly Setting<bool> shareImageUpdated = new Setting<bool>("shareImageUpdated", false);
public static readonly Setting<bool> linkImageUpdated = new Setting<bool>("linkImageUpdated", false);
TileItem.cs
public class TileItem
{
//public string ImageUri
//{
// get;
// set;
//}
public BitmapImage ImageUri
{
get;
set;
}
public string Title
{
get;
set;
}
public string Notification
{
get;
set;
}
public bool DisplayNotification
{
get
{
return !string.IsNullOrEmpty(this.Notification);
}
}
public string Message
{
get;
set;
}
public string GroupTag
{
get;
set;
}
//for translation purposes (bound to HubTile Title on MainPage)
public string TileName
{
get;
set;
}
}
I do not get any debugging errors when running this application, but it seems thta the bitmaps are not being either saved or retrieved correctly, becuase the original tile image is the only one that persists when the app leaves the MainPage. What am I doing wrong here, and how may I fix this?
Here is the working code for storing image in Isolated storage and Loading it back. Check it.
string tempJPEG = "image.jpg";
void photoTask_Completed(object sender, PhotoResult e)
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (myIsolatedStorage.FileExists(tempJPEG))
{
myIsolatedStorage.DeleteFile(tempJPEG);
}
IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempJPEG);
BitmapImage bitmap = new BitmapImage();
bitmap.SetSource(e.ChosenPhoto);
WriteableBitmap wb = new WriteableBitmap(bitmap);
// Encode WriteableBitmap object to a JPEG stream.
Extensions.SaveJpeg(wb, fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
//wb.SaveJpeg(fileStream, wb.PixelWidth, wb.PixelHeight, 0, 85);
fileStream.Close();
}
}
//Code to load image from IsolatedStorage anywhere in your app
private void Button_Click_1(object sender, RoutedEventArgs e)
{
BitmapImage bi = new BitmapImage();
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile(tempJPEG, FileMode.Open, FileAccess.Read))
{
bi.SetSource(fileStream);
this.img.Height = bi.PixelHeight;
this.img.Width = bi.PixelWidth;
}
}
this.img.Source = bi;
}

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

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.

Categories