Image processing for windows phone - image

im searching for a good imaging SDK for windows phone ...
i tried to use Nokia SDK but it didn't work for me, it keeps showing as exception:
"Operation Is Not Valid Due To The Current State Of The Object."
here is my test code:
The processImage method is used to apply the filter on the image.
private async void processImage()
{
WriteableBitmap writeableBitmap = new WriteableBitmap((int)bitmapImage.PixelWidth, (int)bitmapImage.PixelHeight);
try
{
using (var imageStream = new StreamImageSource(photoStream))
{
// Applying the custom filter effect to the image stream
using (var customEffect = new NegateFilter(imageStream))
{
// Rendering the resulting image to a WriteableBitmap
using (var renderer = new WriteableBitmapRenderer(customEffect, writeableBitmap))
{
// Applying the WriteableBitmap to our xaml image control
await renderer.RenderAsync();
imageGrid.Source = writeableBitmap;
}
}
}
}
catch (Exception exc) { MessageBox.Show(exc.Message + exc.StackTrace, exc.Source, MessageBoxButton.OK); }
}
This is the NegateFilter class:
namespace ImagingTest
{
class NegateFilter : CustomEffectBase
{
public NegateFilter(IImageProvider source) : base(source){}
protected override void OnProcess(PixelRegion sourcePixelRegion, PixelRegion targetPixelRegion)
{
sourcePixelRegion.ForEachRow((index, width, pos) =>
{
for (int x = 0; x < width; ++x, ++index)
{
targetPixelRegion.ImagePixels[index] = 255 - sourcePixelRegion.ImagePixels[index];
}
});
}
}
}
any ideas for a good imaging SDK? like ImageJ on java for example, or OpenCV ..
i will be better to use Nokia SDK ..
thx :)

I looked in to you code and did a quick test.
The code worked fine when I just made sure that the bitmapImage.PixelWidth and bitmapImage.PixelHeight > 0.
I did not get and image on the screen but when I remove your custom filter the image is show.
I hope you will continue to use the SDK since it is a great product.

What about emguCV?
I am not try it yet but looks like it's possible with phone's camera.

Related

Xamarin IMediaPicker shows gallery in wrong size in iPad

I'm using the IMediaPicker lines to open gallery and pick an image:
using XLabs.Platform.Services.Media;
using XLabs.Platform.Device;
using XLabs.Ioc;
using Xamarin.Forms;
private async Task<string> pickImage(){
var device = Resolver.Resolve<IDevice>();
IMediaPicker mediaPicker = DependencyService.Get<IMediaPicker>() ?? device.MediaPicker;
if (mediaPicker == null)
throw new NullReferenceException("Media picker initialize error");
string ImageSource = null;
try
{
if (mediaPicker.IsPhotosSupported)
{
var mediaFile = await mediaPicker.SelectPhotoAsync(new CameraMediaStorageOptions
{
MaxPixelDimension = 400
});
ImageSource = mediaFile.Path;
}
}
catch (System.Exception)
{
}
return ImageSource;
}
However when I trigger the function in iPad it look like this:
The gallery only shows up as the size of an iPhone4 and there seems to be no where to change the frame or size. All I want is to display a full screen for it.
It worked well in android tablets.
Is there a work around?

Base64ToImage in Windows 8 Store App

In my Windows 8 app I get an image as base64 string. Now I am looking for a method that converts the string so that I can include it in my XAML image, something like this:
public static Image Base64ToImage(string s)
{
// How To?
}
I have seen many solutions but all of them use classes/methods that are not available in Windows 8 store apps. Thanks for your hints.
The method could look like this:
private async Task<BitmapImage> Base64ToImage(string base64)
{
var bitmap = new BitmapImage();
var buffer = Convert.FromBase64String(base64);
using (var stream = new InMemoryRandomAccessStream())
{
await stream.WriteAsync(buffer.AsBuffer());
stream.Seek(0);
bitmap.SetSource(stream);
}
return bitmap;
}

Binding Image stored in the Isolated Storage to Image Control in Windows Phone

Is it possible to bind the image present in the Isolates storage to image control through xaml. I found some implementations like getting the image through the property and binding that into xaml control. But this is not the implementation what I am searching for. My question is like, writing an attach property and helper method to fetch the content from Isolated storage. I found a similar implementation in LowProfileImage class, used in windows phone 7. But I think it is deprecated now. If anyone tried similar implementations please help me to achieve the same. Also if implementation have any performance drains please mention that info too.
Yes, it is possible to use images from isolated storage in the app UI. It requires loading the image from the file into the BitmapImage and then binding ImageSource of your control to that BitmapImage. I'm using the following approach:
First, there's a method to load image asynchronously:
private Task<Stream> LoadImageAsync(string filename)
{
return Task.Factory.StartNew<Stream>(() =>
{
if (filename == null)
{
throw new ArgumentException("one of parameters is null");
}
Stream stream = null;
using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoStore.FileExists(filename))
{
stream = isoStore.OpenFile(filename, System.IO.FileMode.Open, FileAccess.Read);
}
}
return stream;
});
}
Then it can be used like this:
public async Task<BitmapSource> FetchImage()
{
BitmapImage image = null;
using (var imageStream = await LoadImageAsync(doc.ImagePath))
{
if (imageStream != null)
{
image = new BitmapImage();
image.SetSource(imageStream);
}
}
return image;
}
And finally you just assign return value of FetchImage() method to some of your view model's property, to which the UI element is bound. Of course, your view model should properly implement INotifyPropertyChanged interface for this approach to work reliably.
If you want to use attached properties approach, here's how you do it:
public class IsoStoreImageSource : DependencyObject
{
public static void SetIsoStoreFileName(UIElement element, string value)
{
element.SetValue(IsoStoreFileNameProperty, value);
}
public static string GetIsoStoreFileName(UIElement element)
{
return (string)element.GetValue(IsoStoreFileNameProperty);
}
// Using a DependencyProperty as the backing store for IsoStoreFileName. This enables animation, styling, binding, etc...
public static readonly DependencyProperty IsoStoreFileNameProperty =
DependencyProperty.RegisterAttached("IsoStoreFileName", typeof(string), typeof(IsoStoreImageSource), new PropertyMetadata("", Changed));
private static void Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
Image img = d as Image;
if (img != null)
{
var path = e.NewValue as string;
SynchronizationContext uiThread = SynchronizationContext.Current;
Task.Factory.StartNew(() =>
{
using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isoStore.FileExists(path))
{
var stream = isoStore.OpenFile(path, System.IO.FileMode.Open, FileAccess.Read);
uiThread.Post(_ =>
{
var _img = new BitmapImage();
_img.SetSource(stream);
img.Source = _img;
}, null);
}
}
});
}
}
}
And then in XAML:
<Image local:IsoStoreImageSource.IsoStoreFileName="{Binding Path}" />
Some limitations of this approach:
It only works on Image control, though you can change this to a whichever type you want. It's just not very generic.
Performance-wise, it will use a thread from the threadpool every time image source is changed. It's the only way to do asynchronous read from isolated storage on Windows Phone 8 right now. And you definitely don't want to do this synchronously.
But it has one one important advantage:
It works! :)
I like the above approach but there is a simpler more hacky way of doing it if you are interested.
You can go into your xaml and bind the image source to an string property then put the file path into the property dynamically.
<!-- XAML CODE -->
<Image Source="{Binding imagePath}"/>
//Behind property
public String imagePath { get; set; }
load your path into the image path then bind the image source to the image path string. You might have to do an INotifyPropertyChanged but this method should work with proper binding.

Unable to draw a simple image using JComponent

I'm using netbeans IDE to practice some Java basic code. But I'm unsuccessful to draw a PNG image. Below is my code,
package JavaApplication1;
import javax.swing.*;
import java.awt.*;
class MyCanvas extends JComponent
{
Image img;
public MyCanvas(){
img = Toolkit.getDefaultToolkit().createImage("pengbrew.png");
}
public void paintComponent(Graphics g){
super.paintComponent(g);
g.drawImage(img, 0, 0, null);
}
}
public class JavaGame
{
public static void main(String args[]){
JFrame window = new JFrame("Image demo");
window.getContentPane().add( new MyCanvas() );
window.setSize(400,400);
window.setVisible(true);
}
}
I added the images in the netbeans project.
Please advise.
Many thanks.
easiest ways is look for JLabel that's best of JComponents for Icon/ImageIcon examples here
To load an image use ImageIO.read(File file). It's a newer API, easier to use and better supported. A tutorial on loading images is here http://docs.oracle.com/javase/tutorial/2d/images/loadimage.html if you need some more pointers.
Your code would look like this instead,
Image img;
public MyCanvas(){
try {
img = ImageIO.read(new File("pengbrew.png"));
} catch (IOException e) {
// Handle exception if there is one.
}
}
For the long answer about why the method you were using wasn't working is probably because of the following...
Your image may be in the proper location and instead Toolkit.createImage() hasn't finished loading the image before the frame comes up to paint. Toolkit.createImage() returns control back to your application before the underlying image has actually finished being loaded. You can usually verify if this is the issue by resizing your application to force it to repaint. If after a few seconds of trying to resize the application the image shows up it was due to the image not being loaded during the first paint calls.
To ensure that the image is loaded before you continue you need to use a MediaTracker. Here is some example code to ensure loading of Image is complete before using it.
Component component = new Component() {};
MediaTracker TRACKER = new MediaTracker(component);
...
Image image = Toolkit.getDefaultToolkit().createImage("imageToLoad.png");
synchronized(TRACKER) {
int id = ++mediaTrackerID;
TRACKER.addImage(image, id);
try {
TRACKER.waitForID(id, 0);
} catch (InterruptedException ex) {
image = null;
}
TRACKER.removeImage(image, id);
}
// Now you can use your image.
You'll see code just like this in the ImageIcon class in the method loadImage(Image image).

Transition of images in Windows Forms Picture box

I'm new to Windows Forms, in my project, i need to change the image in the picture box at runtime. I'm able to do that with the help of a timer. The picture just gets changed. Is it possible to do some transitions when image changes, for example fade in, fade out, blur etc.. If possible could some one please let me know how to do it. I searched in net but in vain.Thanks in advance.
Varun
Simply take new code file and paste below code in it
an original answer for the similar question, answer taken from another question
Answer
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Windows.Forms;
public class BlendPanel : Panel
{
private Image mImg1;
private Image mImg2;
private float mBlend;
public BlendPanel()
{
SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer, true);
}
public Image Image1
{
get { return mImg1; }
set { mImg1 = value; Invalidate(); }
}
public Image Image2
{
get { return mImg2; }
set { mImg2 = value; Invalidate(); }
}
public float Blend
{
get { return mBlend; }
set { mBlend = value; Invalidate(); }
}
protected override void OnPaint(PaintEventArgs e)
{
if (mImg1 == null || mImg2 == null)
e.Graphics.FillRectangle(new SolidBrush(this.BackColor), new Rectangle(0, 0, this.Width, this.Height));
else
{
Rectangle rc = new Rectangle(0, 0, this.Width, this.Height);
ColorMatrix cm = new ColorMatrix();
ImageAttributes ia = new ImageAttributes();
cm.Matrix33 = mBlend;
ia.SetColorMatrix(cm);
e.Graphics.DrawImage(mImg2, rc, 0, 0, mImg2.Width, mImg2.Height, GraphicsUnit.Pixel, ia);
cm.Matrix33 = 1F - mBlend;
ia.SetColorMatrix(cm);
e.Graphics.DrawImage(mImg1, rc, 0, 0, mImg1.Width, mImg1.Height, GraphicsUnit.Pixel, ia);
}
base.OnPaint(e);
}
}
Build your project. You can now drop a BlendPanel from the top of the toolbox onto your form. Here's a sample program that uses it:
private float mBlend;
private int mDir = 1;
public int count = 0;
public Bitmap[] pictures;
public void myPhoto()
{
pictures = new Bitmap[9];
pictures[0] = new Bitmap(#"Library Images\cf3.jpg");
pictures[1] = new Bitmap(#"Library Images\cf4.jpg");
pictures[2] = new Bitmap(#"Library Images\l1.JPG");
pictures[3] = new Bitmap(#"Library Images\l2.JPG");
pictures[4] = new Bitmap(#"Library Images\l3.JPG");
pictures[5] = new Bitmap(#"Library Images\l4.JPG");
pictures[6] = new Bitmap(#"Library Images\l5.JPG");
pictures[7] = new Bitmap(#"Library Images\l6.JPG");
pictures[8] = new Bitmap(#"Library Images\l7.JPG");
timer1.Interval = 50; //time of transition
timer1.Tick += BlendTick;
try
{
blendPanel1.Image1 = pictures[count];
blendPanel1.Image2 = pictures[++count];
}
catch
{
}
timer1.Enabled = true;
}
private void BlendTick(object sender, EventArgs e)
{
mBlend += mDir * 0.02F;
if (mBlend > 1)
{
mBlend = 0.0F;
if ((count + 1) < pictures.Length)
{
blendPanel1.Image1 = pictures[count];
blendPanel1.Image2 = pictures[++count];
}
else
{
blendPanel1.Image1 = pictures[count];
blendPanel1.Image2 = pictures[0];
count = 0;
}
}
blendPanel1.Blend = mBlend;
}
You'll need to modify the new Bitmap(#"yourimagePath"); calls. Build and run. You should see the displayed image smoothly morph from your first image to your second image without any flickering.
I hope it helps for other...
There is no built-in support for such effects, but you can implement them. I'd suggest to write a custom control that renders the image and have a method for fade-swap, fade itself can be reached with alpha-blending drawing with .NET Graphics class.
However, Graphics class isn't very fast, I don't recommend to use this technique for big images. If you need some fancy UI with hw-accelerated effects, take a look at WPF.
Blend effects are easy to get going by using the ColorMatrix class. There's a good example available in my answer in this thread.
A simple way to get a blur is to resize the image, making it smaller, then redraw it back, making it larger. The Graphics.InterpolationMode property affects the type of blur you'll get.
Those are quicky do-it-yourself solutions. Any decent graphics library has these kind of operations built-in. You probably want something free, check out ImageMagick.NET
To put it simply, not without external (3rd-party) libraries.

Resources