How to download images from image urls in windows phone8 using asynctask - windows-phone-8

I'm having 10 image urls. I want to download those images and htmls to local folder and replace the image paths in corresponding image source of htmls. How to download 10 images from urls. below code for single image download.
var webClient = new WebClient();
webClient.OpenReadCompleted += WebClientOpenReadCompleted;
webClient.OpenReadAsync(new Uri(webimages["image url"], UriKind.Absolute));
void WebClientOpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
const string tempJpeg = "TempJPEG";
var streamResourceInfo = new StreamResourceInfo(e.Result, null);
var userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication();
if (userStoreForApplication.FileExists(tempJpeg))
{
// userStoreForApplication.DeleteFile(tempJpeg);
MessageBox.Show("Image Already Exists");
}
var isolatedStorageFileStream = userStoreForApplication.CreateFile(tempJpeg);
var bitmapImage = new BitmapImage { CreateOptions = BitmapCreateOptions.None };
bitmapImage.SetSource(streamResourceInfo.Stream);
var writeableBitmap = new WriteableBitmap(bitmapImage);
writeableBitmap.SaveJpeg(isolatedStorageFileStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 85);
isolatedStorageFileStream.Close();
isolatedStorageFileStream = userStoreForApplication.OpenFile(tempJpeg, FileMode.Open, FileAccess.Read);
// Save the image to the camera roll or saved pictures album.
var mediaLibrary = new MediaLibrary();
// Save the image to the saved pictures album.
mediaLibrary.SavePicture(string.Format("SavedPicture{0}.jpg", DateTime.Now), isolatedStorageFileStream);
isolatedStorageFileStream.Close();
}

Related

How to get a dataurl base 64 encoding from a canvas but only for a sub image?

I have a canvas, and I want to get a base64 encoding from it to send to server, which I can do with .toDataURL(). But the problem is I don't want to send the whole image, I want to send a portion of it. I then have
.getImageData(x, y, w, h) to get the image data of the portion. But now how can I get the data url of this to send to the server?
Does anyone know?
Thanks
Just create a temp canvas and copy the pixels to the canvas then get the data URL of that canvas
// context is the context from which to copy
// x,y,w,h is the sub area to copy ar data URL
function getDataURLSubImage(context,x,y,w,h){
var can = document.createElement("canvas");
can.width = w;
can.height = h;
var ctx = can.getContext("2d");
ctx.drawImage(context.canvas,-x,-y);
return can.toDataURL();
}
Or if you only have imageData you can do the following but it is less efficient than the above method.
function imageDataToDataURL(imageData){
var can = document.createElement("canvas");
can.width = imageData.width;
can.height = imageData.height;
var ctx = can.getContext("2d");
ctx.putImageData(imageData,0,0);
return can.toDataURL();
}
In javascript, the dataURL can be sent in JSON format.
$scope.canvasObject = {
"screenName" : 'testName',
"screenObject" : JSON.stringify(canvas.toDataURL())
};
In serverside, this will be received in byte array format.
byte[] bytes = null;
File file = null;
BufferedImage bfi = null;
try {
if (entity != null && entity.getScreenObject() != null) {
bytes = DatatypeConverter
.parseBase64Binary(entity.getScreenObject().replaceAll("data:image/png;base64,", ""));
file = new File(entity.getScreenName() + System.currentTimeMillis() + ".png");
bfi = ImageIO.read(new ByteArrayInputStream(bytes));
ImageIO.write(bfi, "png", file);
bfi.flush();
}
} catch (Exception e) {
// handle exception
}
This saves the image in server.

Alarm with song from Music store

I am new to Windows Phone 8 platform and I want to develop an application for showing alarm.
In that I need to put an option for selecting the alarm sound from music store. Here I want to know how to set an alarm with song from music store.
Try this snippet out.
Alarm alarm = new Alarm(name);
alarm.Content = contentTextBox.Text;
alarm.Sound = new Uri("/Ringtones/Ring01.wma", UriKind.Relative);
alarm.BeginTime = beginTime;
alarm.ExpirationTime = expirationTime;
alarm.RecurrenceType = recurrence;
ScheduledActionService.Add(alarm);
For more take a look over here
Use WebClient to download the alarm sound from server
WebClient client = new WebClient();
Uri uri = new Uri(songUrl);
client.OpenReadCompleted += new OpenReadCompletedEventHandler(OpenReadCallback2);
client.OpenReadAsync(uri);
In the OpenReadCallback2
private void OpenReadCallback2(object sender, OpenReadCompletedEventArgs e)
{
byte[] buffer = new byte[e.Result.Length];
e.Result.Read(buffer, 0, buffer.Length);
using (var fs = File.Create("file.mp3"))
{
fs.Write(buffer, 0, buffer.Length);
}
Save stream in to a file named "file.mp3"
Now create your alarm
Alarm objAlarm = ScheduledActionService.Find("samplealarm123") as Alarm;
if (objAlarm != null)
ScheduledActionService.Remove("samplealarm123");
objAlarm = new Alarm("samplealarm123");
objAlarm.Content = "sample alarm";
objAlarm.Sound = new Uri("/file.mp3", UriKind.Relative); ;
objAlarm.BeginTime = dt;// datetime.now.addminutes(1);
objAlarm.ExpirationTime = dt.AddMinutes(1);
ScheduledActionService.Add(objAlarm);
This will play the song downloaded from server as Alarm tune.

How can I use Writablebitmap in ScheduledTask in windows phone 8?

I want to update my live tile by creating and saving a writable bitmap image in scheduled task agent.my code works inside the app but in background task, it breaks into the debugger
I'm using this simple code:
protected override void OnInvoke(ScheduledTask task)
{
#if DEBUG_AGENT
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(30));
#endif
CreateWideTile();
NotifyComplete();
}
and my code to create and save image is this:
private void CreateWideTile()
{
int width = 691;
int height = 336;
string imagename = "WideBackground";
WriteableBitmap b = new WriteableBitmap(width, height);
var canvas = new Grid();
canvas.Width = b.PixelWidth;
canvas.Height = b.PixelHeight;
var background = new Canvas();
background.Height = b.PixelHeight;
background.Width = b.PixelWidth;
//Created background color as Accent color
SolidColorBrush backColor = new SolidColorBrush(Colors.Red);
background.Background = backColor;
var textBlock = new TextBlock();
textBlock.Text = "Example text";
textBlock.FontWeight = FontWeights.Normal;
textBlock.TextAlignment = TextAlignment.Left;
textBlock.Margin = new Thickness(20, 20, 0, 0);
textBlock.TextWrapping = TextWrapping.Wrap;
textBlock.Foreground = new SolidColorBrush(Colors.White); //color of the text on the Tile
textBlock.FontSize = 30;
canvas.Children.Add(textBlock);
b.Render(background, null);
b.Render(canvas, null);
b.Invalidate(); //Draw bitmap
//Save bitmap as jpeg file in Isolated Storage
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream imageStream = new IsolatedStorageFileStream("/Shared/ShellContent/" + imagename + ".jpg", System.IO.FileMode.Create, isf))
{
b.SaveJpeg(imageStream, b.PixelWidth, b.PixelHeight, 0, 100);
}
}
}
when I test the app, after executing background task, an error comes that point to Debugger.Break();
private static void UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (Debugger.IsAttached)
{
// An unhandled exception has occurred; break into the debugger
Debugger.Break();
}
}
I don't understand the reason. my code works in foreground app but not in background ...
any solution ????
You should use dispatcher, because WriteableBitmap.Render should be used in the UI thread:
protected override void OnInvoke(ScheduledTask task)
{
Deployment.Current.Dispatcher.BeginInvoke( () =>
{
CreateWideTile();
NotifyComplete();
} );
}

Windows Phone - WriteableBitmap.Render does not work with InkPresenter

I'm using WriteableBitmap.Render to convert an InkPresenter control to a byte array and Image.
This is my code:
var bitmap = new WriteableBitmap(element, null);
bitmap.Render(element, null);
bitmap.Invalidate();
BitmapImage img;
using (var ms = new MemoryStream())
{
bitmap.SaveJpeg(ms, bitmap.PixelWidth, bitmap.PixelHeight, 0, 85);
// byte[] bytes = ms.ToArray();
img = new BitmapImage();
img.SetSource(ms);
}
If I save the result (byte array or Image) into IsoladtedStorage, the Image has the correct size but is only black.
I don't have an idea why it does not work because I've already used this method with the Map control.
using (var stream = new MemoryStream())
{
WriteableBitmap dd = new WriteableBitmap(ink, null);
dd.SaveJpeg(stream, dd.PixelWidth, dd.PixelHeight, 0, 100);
stream.Seek(0, SeekOrigin.Begin);
var ml = new MediaLibrary();
ink.Background = new SolidColorBrush(Colors.White);
ml.SavePicture(string.Format("Images\\{0}.jpg", Guid.NewGuid()), stream);
ink.Background = new SolidColorBrush(Colors.Transparent);
}

Object Data Type in AS3 and Flash Builder 4.5.1

I am trying to save a Sprite object as a file on the device I'm working on and it seems to work. the problem I'm having is reading the saved file back and placing it back on stage as a sprite. Below is the code I have so far, could someone tell me what it is I'm doing wrong? I have a suspicion that the saved isn't what I expect it to be since the file sizes have been under a kilobyte.
public function save_album(e:Event):void
{
var outFile:File = File.documentsDirectory; // dest folder is desktop
outFile = outFile.resolvePath("canvas3.bin");
var fs:FileStream = new FileStream();
var bytes:ByteArray = new ByteArray();
//trace (File.documentsDirectory.url + "/canvas2.bin");
fs.open(outFile, FileMode.WRITE);
bytes.writeObject(graffitiContainer) //graffitiContainer is a Sprite
bytes.position = 0;
fs.writeBytes(bytes, 0, bytes.length);
fs.close();
}
public function open_album(e:Event):void
{
var inBytes:ByteArray = new ByteArray();
var inFile:File = File.documentsDirectory;
inFile = inFile.resolvePath("canvas3.bin"); // name of file to read
var inStream:FileStream = new FileStream();
inStream.open(inFile, FileMode.READ);
inStream.readBytes(inBytes, 0, inBytes.length);
inStream.close();
inBytes.position = 0;
ui.removeChild(graffitiContainer);
var obj:Sprite = inBytes.readObject() as Sprite; //returns a null
graffitiContainer = obj;
ui = new UIComponent();
graffitiContainer.x = 0;
graffitiContainer.y = 100;
ui.addChild(graffitiContainer);
}
Not fully sure I understand what you're trying to accomplish; however, this implementation doesn't do what you're thinking - writeObject could only serialize general public properties, and not the graphics member.
You could render it to a Bitmap.
Saw a blog post about this:
http://jacwright.com/201/serializing-display-objects/