How can I generate a Image in ScheduledAgent? - c#

I'm unsure on how I can go from WriteAbleBitmap to IconicTileData's url property IconImage.
Here is my code so far:
protected override void OnInvoke(ScheduledTask task)
{
ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault();
if (tile != null)
{
WriteableBitmap genTile = renderTile(202, 202);
tile.Update(new IconicTileData()
{
Title = "IconicTileData",
IconImage = /* PATH TO genTile */
});
}
ScheduledActionService.LaunchForTest(task.Name, TimeSpan.FromSeconds(3));
NotifyComplete();
}
private WriteableBitmap renderTile(int width, int height)
{
Canvas can = new Canvas();
can.Background = new SolidColorBrush(Color.FromArgb(255, 0, 255, 0));
can.Width = width;
can.Height = height;
WriteableBitmap tileImage = new WriteableBitmap(width, height);
tileImage.Render(can, null);
tileImage.Invalidate();
return tileImage;
}
The solution would be to save the file? How can I do that, ShellTile does not share the same space as the application?

Save the file to isolated storage, and then use the "isostore:" prefix in the Uri.
public static void StoreSavedResultImage(string filename, WriteableBitmap wb)
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isf.FileExists(filename))
isf.DeleteFile(filename);
using (IsolatedStorageFileStream fs = isf.CreateFile(filename))
{
wb.SaveJpeg(fs, wb.PixelWidth, wb.PixelHeight, 0, 100);
fs.Close();
wb = null;
img = null;
}
}
}
If you want to reference a file from isolated storage in a live tile, the file should be saved in the /Shared/ShellContent folder.
Uri wideUri = new Uri("isostore:/Shared/ShellContent/app_wide.jpg"), UriKind.Absolute);
tile.Update(new IconicTileData()
{
Title = "IconicTileData",
IconImage = wideUri
});

Related

bitmap loaded memory increase 10x the size of the file

I am loading an image and i get an increase of memory around 10x the size of the file.
this is the output for the code below
Loading file img_6.jpg with originally 513kb
Memory for image img_6.jpg is 63704kb (124.12x)
Thanks!
this is the code i use to load
string filename = "img_6.jpg";
Directory.SetCurrentDirectory(#"C:\Users\Admin\Desktop\isolated images");
Helpers.membefore(filename);
BitmapImage bitmap = new BitmapImage();
//using (Stream stream = new FileStream(filepath, FileMode.Open))
{
bitmap.BeginInit();
//bitmap.StreamSource = stream;
bitmap.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
bitmap.CacheOption = BitmapCacheOption.OnLoad;
bitmap.UriSource = new Uri(filename, UriKind.Relative);
bitmap.EndInit();
}
ImageBrush ib = new ImageBrush() { ImageSource = bitmap };
Helpers.memafter(ib);
these are the memory log helpers
public static void memafter(object result)
{
//debugging
if (result.GetType() == typeof(ImageBrush) && (result as ImageBrush).ImageSource != null)
{
var after = Process.GetCurrentProcess().VirtualMemorySize64;
string factor = ((double)(after - before) / (double)len).ToString("N") ;
string source = (result as ImageBrush).ImageSource.ToString();
Console.WriteLine(String.Format("Memory for image {0} is {1}kb ({2}x)",
source,
(after - before) / 1024,
factor.ToString()));
string s = result.ToString();
}
}
public static void membefore(string xaml)
{
FileInfo fi = new FileInfo(xaml);
len = fi.Length;
Console.WriteLine(string.Format("Loading file {0} with originally {1}kb", xaml, fi.Length / 1024));
if (xaml.Contains("ico") || xaml.Contains("jpg") || xaml.Contains("bmp") || xaml.Contains("png"))
{
before = Process.GetCurrentProcess().VirtualMemorySize64;
}
}
private static long len = 0;
static long before = 0;
Ok right,
the reason there are different file formats was behind it.
Irfanview helped a lot with pressing I opening image information shows file and loaded memory size.

About enlarging the captured screenshot size

I am trying to enlarge the size of screenshot without losing quality (as possible), but I can not do this. I am processing this picture in another method and filestream stop working. Actually tesseract can not read because of the screenshot's size so I am trying to enlarge the size of screenshot but I can not change the size of screenshot during capturing.
private void button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(4000);
Snapshot().Save("D:\\program_goruntusu.jpg");
string s = FotoAnaliz();
}
private Bitmap Snapshot()
{
Bitmap Screenshot = new Bitmap(20, 20);
Graphics GFX = Graphics.FromImage(Screenshot);
GFX.CopyFromScreen(1243, 349, 0, 0, new Size(20, 20));
return Screenshot;
}
private string FotoAnaliz()
{
FileStream fs = new FileStream("D:\\program_goruntusu.jpg", FileMode.OpenOrCreate);
//string fotopath = #"D:\\program_goruntusu.jpg";
Bitmap images = new Bitmap(fs);
using (var engine = new TesseractEngine(#"./tessdata", "eng"))
{
engine.SetVariable("tessedit_char_whitelist", "0123456789");
// have to load Pix via a bitmap since Pix doesn't support loading a stream.
using (var image = new Bitmap(images))
{
using (var pix = PixConverter.ToPix(image))
{
using (var page = engine.Process(pix))
{
sayı = page.GetText();
MessageBox.Show(sayı);
fs.Close();
}
}
}
}
return sayı;
}

WPF Add a button with image and style dynamically

My objective is as follows: I want to drag drop a file to my WPF window and it should create a button with the icon image at run time.
Currently my code simply creates a button without any image in it. Im new to WPF so please go easy on me!
public static readonly DependencyProperty ImageSourceProperty = DependencyProperty.RegisterAttached("ImageSource", typeof(ImageSource), typeof(AttachedProperties), new UIPropertyMetadata(null));
public static void SetImageSource(DependencyObject d, ImageSource source)
{
d.SetValue(ImageSourceProperty, source);
}
private Bitmap GetIconImageFromFile(String filename)
{
Bitmap bmp = System.Drawing.Icon.ExtractAssociatedIcon(filename).ToBitmap();
bmp.Save("test.bmp");
return bmp;
}
private BitmapImage GetBitmapImageFromBitmap(Bitmap bitmap)
{
BitmapImage bitmapImage = new BitmapImage();
using (MemoryStream memory = new MemoryStream())
{
bitmap.Save(memory, ImageFormat.Png);
memory.Position = 0;
memory.Seek(0, SeekOrigin.Begin);
bitmapImage.BeginInit();
bitmapImage.StreamSource = memory;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
}
return bitmapImage;
}
private void Window_Drop(object sender, System.Windows.DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop) == true)
{
String[] fileNames = (String[])e.Data.GetData(DataFormats.FileDrop);
foreach (String fileName in fileNames)
{
MessageBox.Show("WindowDrop " + fileName);
Button newButton = new Button();
newButton.Width = 100;
newButton.Height = 50;
//newButton.Template = (ControlTemplate)TryFindResource("btemp2");
Bitmap bmp = GetIconImageFromFile(fileName);
BitmapSource src = GetBitmapImageFromBitmap(bmp);
AttachedProperties.SetImageSource(newButton,src);
stack.Children.Add(newButton);
}
}
}
I have modified your code as follows , I create Image instance and set it as button content. Please try this.
foreach (String fileName in fileNames)
{
MessageBox.Show("WindowDrop " + fileName);
Button newButton = new Button();
newButton.Width = 100;
newButton.Height = 50;
//Craete the Image isntance and set the image to be dispalyed
Image ButtonPicture = new Image();
ButtonPicture.BaseUri = fileName;
//Set it to the button content
newButton.Content = ButtonPicture;
AttachedProperties.SetImageSource(newButton,src);
stack.Children.Add(newButton);
}

Load image from url to ImageView - C#

I want to load an image from url to imageview in c# ( android programming ) after search in google i cant find any good result , thank you for helping
i am using xamarin studio
The very first hit I got from Google was a thread on the Xamarin forums discussing this exact issue:
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
imageBitmap = BitmapFactory.DecodeByteArray(imageBytes, 0, imageBytes.Length);
}
}
return imageBitmap;
}
var imageBitmap = GetImageBitmapFromUrl("http://xamarin.com/resources/design/home/devices.png");
imagen.SetImageBitmap(imageBitmap);
Both approaches work, but is a good practice to do it asynchronously. Here you have some good examples:
Asynchronous Image Loading in Xamarin Android http://javatechig.com/xamarin/asynchronous-image-loading-xamarin-android
xamarin-store-app image helper https://github.com/xamarin/xamarin-store-app/blob/master/XamarinStore.Droid/Helpers/Images.cs
Am using the below class in Xamarin Android:
public class DownloadImageTask : AsyncTask
{
private ImageView bmImage;
private ProgressBar progressBar;
public DownloadImageTask( ImageView bmImage , ProgressBar progressBar)
{
this.bmImage = bmImage;
this.progressBar = progressBar;
}
protected override void OnPostExecute( Object result )
{
base.OnPostExecute(result);
bmImage.SetImageBitmap(( Bitmap ) result);
if (progressBar != null)
progressBar.Visibility = ViewStates.Gone;
}
protected override Object DoInBackground( params Object[] #params )
{
var urldisplay = #params[0].ToString();
Bitmap mIcon11 = null;
try
{
var req = WebRequest.Create(urldisplay);
var response = req.GetResponse();
var stream = response.GetResponseStream();
mIcon11 = BitmapFactory.DecodeStream(stream);
}
catch ( Exception e )
{
}
return mIcon11;
}
}
Execution :
new DownloadImageTask(imgProfile , progressBar).Execute(uri);
I did this to load an Svg from an url into an ImageView using SkiaSharp.
In the .xml
<ImageView
android:contentDescription=""
android:id="#+id/video_recorder_image"
android:layout_width="wrap_content"
android:layout_height="50dp" />
In the activity/fragment.
private ImageView iconImageView;
public override void OnViewCreated(View view, Bundle savedInstanceState)
{
iconImageView = (ImageView)view.FindViewById(Resource.Id.video_recorder_image);
Bitmap image = GetImageBitmapFromUrl(_iconUrl);
}
private Bitmap GetImageBitmapFromUrl(string url)
{
Bitmap imageBitmap = null;
using (var webClient = new WebClient())
{
var imageBytes = webClient.DownloadData(url);
if (imageBytes != null && imageBytes.Length > 0)
{
var svgContent = Convert.ToBase64String(imageBytes, 0, imageBytes.Length);
var byteArray = Convert.FromBase64String(svgContent);
using (var stream = new MemoryStream(byteArray))
{
var bitmap = new SKBitmap(500, 500);
var canvas = new SKCanvas(bitmap);
// load the SVG
var svg = new SkiaSharp.Extended.Svg.SKSvg(new SKSize(500, 500));
svg.Load(stream);
// draw the SVG to the bitmap
canvas.DrawPicture(svg.Picture);
var skData = SKImage.FromBitmap(bitmap).Encode(SKEncodedImageFormat.Png, 100);
// Convert image to string and then to Bitmap
var convertedSvgStream = skData.AsStream();
var convertedImageBytes = new byte[(int)convertedSvgStream.Length];
convertedSvgStream.Seek(0, SeekOrigin.Begin);
convertedSvgStream.Read(convertedImageBytes, 0, (int)convertedSvgStream.Length);
imageBitmap = BitmapFactory.DecodeByteArray(convertedImageBytes, 0, convertedImageBytes.Length);
}
}
}
return imageBitmap;
}

How do I take a bitmap image and save as a JPEG image file on a Windows Phone 7 device?

I am looking to create a function that takes a BitmapImage and saves it as a JPEG on the local Windows Phone 7 device in isolated storage:
static public void saveImageLocally(string barcode, BitmapImage anImage)
{
// save anImage as a JPEG on the device here
}
How do I accomplish this? I'm assuming I used IsolatedStorageFile somehow?
Thanks.
EDIT:
Here is what I have found so far... can anyone confirm if this is the correct way to do this?
static public void saveImageLocally(string barcode, BitmapImage anImage)
{
WriteableBitmap wb = new WriteableBitmap(anImage);
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var fs = isf.CreateFile(barcode + ".jpg"))
{
wb.SaveJpeg(fs, wb.PixelWidth, wb.PixelHeight, 0, 100);
}
}
}
static public void deleteImageLocally(string barcode)
{
using (IsolatedStorageFile MyStore = IsolatedStorageFile.GetUserStoreForApplication())
{
MyStore.DeleteFile(barcode + ".jpg");
}
}
static public BitmapImage getImageWithBarcode(string barcode)
{
BitmapImage bi = new BitmapImage();
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (var fs = isf.OpenFile(barcode + ".jpg", FileMode.Open))
{
bi.SetSource(fs);
}
}
return bi;
}
To save it:
var bmp = new WriteableBitmap(bitmapImage);
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream stream = storage.CreateFile(#"MyFolder\file.jpg"))
{
bmp.SaveJpeg(stream, 200, 100, 0, 95);
stream.Close();
}
}
Yes, the stuff you added in your edit is exactly what I have done before :) it works.
This is my code but you can take the neccesary points from there:
var fileName = String.Format("{0:}.jpg", DateTime.Now.Ticks);
WriteableBitmap bmpCurrentScreenImage = new WriteableBitmap(480, 552);
bmpCurrentScreenImage.Render(yourCanvas, new MatrixTransform());
bmpCurrentScreenImage.Invalidate();
SaveToMediaLibrary(bmpCurrentScreenImage, fileName, 100);
public void SaveToMediaLibrary(WriteableBitmap bitmap, string name, int quality)
{
using (var stream = new MemoryStream())
{
// Save the picture to the Windows Phone media library.
bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, quality);
stream.Seek(0, SeekOrigin.Begin);
new MediaLibrary().SavePicture(name, stream);
}
}

Categories

Resources