Showing posts with label WriteableBitmap. Show all posts
Showing posts with label WriteableBitmap. Show all posts

Wednesday, January 23, 2019

My 10-Year Challenge - WriteableBitmapEx turns 10 with v1.6

It was 2009 when I started my first open source project and announced it with this unspectacular blog post. Back then it was developed with Visual Studio 2008 targeting Silverlight and hosted on CodePlex.
Many things have changed and tech comes and goes but during the last 10 years I always adapted, extended it, added bug fixes and reviewed/merged Pull Requests. Even after all the years WriteableBitmapEx is still quite popular, especially with Windows desktop WPF developers.

Version 1.6.2 of WriteableBitmapEx finally adds dedicated libs for UWP and an UWP sample. For WPF it now supports .NET Core, both the .NET Framework and .NET Core libs are part of the NuGet pack.

If you are using the source code and the VS solution directly, you can choose the .NET Framework 4.5 or .NET Core 3 as the target in the VS drop-down.



WriteableBitmapEx supports a variety of Windows platforms and versions.
WPF and Windows 10 Universal Windows Platform (UWP) are actively maintained.
Silverlight, Windows 8/8.1 WinRT, Windows Phone WinRT and Silverlight 7/8/8.1 are not maintained anymore but the latest stable libs are still part of the NuGet package.

You can download the latest via the updated NuGet package. The packages contain the WriteableBitmapEx binaries. All samples and the source code can be found in the GitHub repository.

A huge shout out and thank you to all the contributors, bug issuers and users of the library. ❤

Friday, May 5, 2017

Long time no hear - WriteableBitmapEx 1.5.1 is out

Even after all the years WriteableBitmapEx is still quite popular, especially with WPF developers and I always incorporate bug fixes and also accept Pull Requests if I get some time.
Many contributions were integrated and lots of bugs fixed. Among those are some nice additions like a clipped line drawing or a dotted line renderer.

WriteableBitmapEx supports a variety of Windows platforms and versions: WPF, Silverlight, Windows 10 Universal Windows Platform (UWP), Windows 8/8.1, Windows Phone WinRT and Silverlight 7/8/8.1.

You can download the latest via the updated NuGet package. The packages contain the WriteableBitmapEx binaries. All samples and the source code can be found in the GitHub repository.

A big thank you to all the contributors, bug reporters and users of the library who help with feedback.

Wednesday, September 23, 2015

We've Come a Long Way Baby - WriteableBitmapEx now on GitHub


The WriteableBitmapEx project is now 6 years old and times have changed since all began. It all started with Silverlight and more XAML flavors were added over time until all XAML flavors were supported including Windows Phone, WPF, WinRT Windows Store XAML, (Windows 10) UWP and still Silverlight.

The version control system and open source services landscape has changed as well and the CodePlex infrastructure has not been too reliable recently. That's why I finally took the time to move the WriteableBitmapEx source code from CodePlex' SVN bridge to Git and make it available on GitHubhttps://github.com/teichgraf/WriteableBitmapEx
Additionally was the open source license changed from Ms-PL to MIT which should simplify the usage as well. See the Codeplex Issue Tracker for a list of features that will be added in the future. Please use the GitHub Issues functionality to add new issues which are not already reported. Of course the latest binaries will continue to be distributed via NuGet.

Tuesday, March 31, 2015

Staying Alive! - WriteableBitmapEx 1.5 is out

After a couple of minor updates on top of version 1.0 which lead to 1.0.14, I'm happy to announce that WriteableBitmapEx 1.5 is now available.
Many contributions were integrated and lots of bugs fixed. Among those are some nice new color modifications and also long awaited DrawLine with variable thickness, pen support, better anti-aliased lines, Cohen-Sutherland line clipping, even-odd polygon filling and alpha-blended shape filling... Read the details at the end of this post or the release notes.

WriteableBitmapEx supports a variety of Windows platforms and versions: WPF, Silverlight, Windows 10 Universal App Platform (UAP), Windows 8/8.1, Windows Phone WinRT and Silverlight 7/8/8.1.


You can download the binaries here or via the NuGet package. The packages contain the WriteableBitmapEx binaries. All samples and the source code can be found in the repository.

A big thank you to all the contributors, bug reporters and users of the library who helped to shape this. You rock!

Changes
  • Added lots of contributions including DrawLine with variable thickness, penning, improved anti-aliasing and Wu's anti-aliasing algorithm
  • Added usage of CohenSutherland line clipping for DrawLineAa and DrawLine, etc.
  • Added support for alpha blended filled shapes and adapted the FillSample for WPF
  • Added FillPolygonsEvenOdd() which uses the even-odd algorithm to fill complex polygons with more than one closed outline like for the letter O
  • Added AdjustBrightness(), AdjustContrast() and AdjustGamma() methods
  • Added Gray() method which returns the gray scaled version the bitmap
  • Fixed regression issue with alpha blending for Blit for non-WinRT
  • Fixed bug in Blit Alpha code for WPF when source format is not pre-multiplied alpha
  • Fixed bug #21778 where FromStream for WPF needs to be called inside Init scope
  • Fixed issue with IndexOutOfRangeEx in DrawLine method
  • Fixed Invalidate for Silverlight BitmapContext.Dispose
  • Fixed many more reported issues
  • ...

Friday, December 20, 2013

How to Encode and Save a WriteableBitmap with Windows WinRT


Windows WinRT 8.1 brought the support of the RenderTargetBitmap and the ability to render the visual tree of the UI into a bitmap. WriteableBitmapEx makes it even easier in the latest version and you might end up in a situation where you want to save a WriteableBitmap to a file or to a stream in general. For that the raw pixel array of the WriteableBitmap needs to be encoded into a common format like JPEG, PNG, etc.

Here's a code snippet how this can be achieved:






private static async Task SaveWriteableBitmapAsJpeg(WriteableBitmap bmp, string fileName)
{
   // Create file in Pictures library and write jpeg to it
   var outputFile = await KnownFolders.PicturesLibrary.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
   using (var writeStream = await outputFile.OpenAsync(FileAccessMode.ReadWrite))
   {
      await EncodeWriteableBitmap(bmp, writeStream, BitmapEncoder.JpegEncoderId);
   }
   return outputFile;
}

private static async Task EncodeWriteableBitmap(WriteableBitmap bmp, IRandomAccessStream writeStream, Guid encoderId)
{         
   // Copy buffer to pixels
   byte[] pixels;
   using (var stream = bmp.PixelBuffer.AsStream())
   {
      pixels = new byte[(uint) stream.Length];
      await stream.ReadAsync(pixels, 0, pixels.Length);
   }

   // Encode pixels into stream
   var encoder = await BitmapEncoder.CreateAsync(encoderId, writeStream);
   encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
      (uint) bmp.PixelWidth, (uint) bmp.PixelHeight,
      96, 96, pixels);
   await encoder.FlushAsync();
}

It's all  pretty straightforward actually: The SaveWriteableBitmapAsJpeg creates a file in the user's pictures library and passes the file's stream and an BitmapEncoder ID on to the EncodeWriteableBitmap method which is doing the actual work. EncodeWriteableBitmap first copies the WriteableBitmap pixel buffer into a byte array, then creates the BitmapEncoder based on the file's stream and the desired BitmapEncoder ID, then sets the pixels and flushes all into the stream.
The BitmapEncoder class supports a couple of BitmapEncoder IDs out of the box like JPEG, PNG and more.

Monday, December 2, 2013

Easy Render! - WriteableBitmapEx now with Better Support for Win 8.1 RenderTargetBitmap


The lack of WriteableBitmap.Render in Windows WinRT 8.0 was quite an issue for many apps, but fortunately did WinRT 8.1 (re-)introduce the RenderTargetBitmap class which provides the functionality of rendering the visual tree of the UI to a bitmap. The new update of WriteableBitmapEx makes it even easier to use with a WriteableBitmap by introducing the FromPixelBuffer method.

WriteableBitmapEx is available for 4 platforms: Windows Phone 8 and 7, WPF, Silverlight and Windows Store WinRT .NET XAML 8 and 8.1.
You can download the binaries here or via the NuGet packageThe packages contain the WriteableBitmapEx binaries. As usual all samples and the source code can be found in the repository.



How to use
The below code snippet shows how a part of the UI can be rendered into a WriteableBitmap via RenderTargetBitmap, how it can be modified and then finally presented back into the UI by using an Image control.

// Render some UI to a RenderTargetBitmap
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(Panel);
            
// Get the pixel buffer and copy it into a WriteableBitmap
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
var width = renderTargetBitmap.PixelWidth;
var height = renderTargetBitmap.PixelHeight;
var wbmp = await new WriteableBitmap(1, 1).FromPixelBuffer(pixelBuffer, width, height);

// Modify the WriteableBitmap
wbmp.FillEllipse(10, 10, 256, 256, Colors.Salmon);
// ... More drawing including writeableBitmap.Blit(...) might go here

// Assign WriteableBitmap to an Image control to present it
ImgMirror.Source = wbmp;

Tuesday, October 30, 2012

Faster! - WriteableBitmapEx for Windows Phone 8 and WinRT Updated

The Windows Phone 8 SDK is now available and with that WriteableBitmapEx was updated too. The performance of the WinRT XAML version was also improved dramatically and an update is highly recommended.
WriteableBitmapEx is available for 4 platforms: Windows Phone 8 and 7, WPF, Silverlight and Windows Store WinRT .NET XAML.
You can download the binaries here or via the NuGet packageThe packages contain the WriteableBitmapEx binaries. As usual all samples and the source code can be found in the repository.

Wednesday, August 29, 2012

Update WriteableBitmapEx for WinRT RTM, WPF, Windows Phone and Silverlight


The RTM version of Windows 8 is now available and with that WriteableBitmapEx was updated too. WriteableBitmapEx is now available for 4 platforms: WPF, Silverlight, Silverlight for Windows Phone and Windows Store Style WinRT .NET.
You can download the binaries here or via the NuGet packageThe packages contain the WriteableBitmapEx binaries. As usual all samples and the source code can be found in the repository.



Since the last WinRT release preview version, a couple of bugs were fixed and a new FromStrean method was added which loads an image stream into a WriteableBitmap. The project was also updated for the Windows 8 RTM version. Please read this blog post for more details about the WinRT version.

Thursday, June 14, 2012

It's Alive! - WriteableBitmapEx 1.0 for WinRT Metro Style, WPF, Windows Phone and Silverlight

After a few preview versions, I'm happy to announce that the final version of WriteableBitmapEx 1.0 is now available.
A couple of weeks ago we added official WPF support and WinRT Metro Style support. With that WriteableBitmapEx is now available for 4 platforms: WPF, Silverlight, Silverlight for Windows Phone and Metro Style WinRT .NET.
You can download the binaries here or via the NuGet package. The packages contain the WriteableBitmapEx binaries. All samples and the source code can be found in the repository.


Since the last WinRT preview version, a new WinRT sample was added, a couple of bugs were fixed and a new FromStrean method was added which loads an image stream into a WriteableBitmap. The project was also updated for the Windows 8 Release Preview. Please read this blog post for more details (about the WinRT version).

Monday, May 7, 2012

One Bitmap to Rule Them All - WriteableBitmapEx for WinRT Metro Style

A couple of weeks ago we added official WPF support to  WriteableBitmapEx. Today I'm happy to announce that WriteableBitmapEx now also officially supports Windows 8 Metro Stlye WinRT .NET XAML. With that WriteableBitmapEx is now available for 4 platforms: WPF, Silverlight, Silverlight for Windows Phone and Metro Style WinRT .NET.
Although Direct2D is the best solution for fast 2D graphics with Windows 8 Metro Style, I think there are scenarios where the WriteableBitmapEx could be helpful, esp. when using C# with XAML. I also know that some devs were waiting for this to port their Windows Phone apps to Windows 8 Metro Style.

WinRT Differences
Unlike the Silverlight WriteableBitmap, the Metro Style WriteableBitmap doesn't provide the pixel data directly. Its IBuffer PixelBuffer property doesn't have an interface to get the color information. Fortunately there are a few C# extension methods available which provide the pixel data as byte array or stream in the BGRA pixel format. Yes, BGRA and not like all the other platforms supported by WriteableBitmapEx as ARGB. The BGRA format is mainly used by Direct2D, which might be the reason for this hidden, but important difference of the Metro Style WriteableBitmap.
The WriteableBitmapEx algorithms are written for the ARGB pixel format. Fortunately I was able to keep the details away from the library user by leveraging the BitmapContext concept we introduced with the WPF support. This approach makes it possible to share almost the same code for all 4 platforms without being cluttered with #if directives all over place.  Actually the most significant WinRT adaptation inside the WriteableBitmapEx methods was done in the FromContent method, which loads an image from the app content and provides it as WriteableBitmap. See this StackOverflow question I answered if you're interested in the details.
Nothing comes for free, but if the BitmapContext is used the right way, the performance hit won't be that much thanks to an internal reference counting WriteableBitmapEx' BitmapContext uses. No worries, you don't have to change all your WriteableBitmapEx calls, just wrap your calls in a simple using(writeableBmp.GetBitmapContext()) and you will only have one buffer conversion instead of one for each draw call.
It's really simple to use:

private void Draw()
{
   // Wrap updates in a GetContext call, to prevent invalidation overhead
   using (writeableBmp.GetBitmapContext())
   {
      writeableBmp.Clear();
      DrawPoints();
      DrawBeziers();
  
   } // Invalidates on exit of using block
}

private void DrawPoints()
{
   foreach (var p in points)
   {
      DrawPoint(p, Colors.Green, PointVisualSizeHalf);
   }
}

private void DrawPoint(ControlPoint p, Color color, int halfSizeOfPoint)
{
   var x1 = p.X - halfSizeOfPoint;
   var y1 = p.Y - halfSizeOfPoint;
   var x2 = p.X + halfSizeOfPoint;
   var y2 = p.Y + halfSizeOfPoint;
   writeableBmp.DrawRectangle(x1, y1, x2, y2, color);
}

private void DrawBeziers()
{
   if (points.Count > 3)
   {
      writeableBmp.DrawBeziers(GetPointArray(), Colors.Yellow);
   }
}

Screenshot WinRT Metro Style sample running in the simulator

All samples were tested with the new version, but due to the refactoring more testing is needed. Please test this version with your projects and report the bugs you encounter. You can download the binaries here. Note that this package only contains the WriteableBitmapEx binaries for Silverlight, Windows Phone, WinRT Metro Style .NET and WPF. All the samples can be found in the source code repository in the branch "WBX_1.0_BitmapContext". If all goes well, this branch will become the trunk and the 1.0 RTM in a few weeks.

WinMD / Windows Runtime Component
There's also a WinMD version available which makes it possible to consume the WriteableBitmapEx library from all the WinRT Metro Style projections, although only C# and C++ XAML make actually sense.
I had to move some parts and leave some functionality like the ForEach out, but it contains 99% of the library's features. Unfortunately the C++ sample I created crashes when the WriteableBitmapExWinMD library is loaded. So for now this WinMD version can be found in a separate branch "WBX_1.0_WinMD" in the source code repository and it won't be part of the trunk and release until it works with the sample. I'm a bit running out of time and don't know where to look for, since it seems all is wired up correctly and compiles fine. If you are a WinMD wizard and have a few minutes, I'd appreciate if you could look into the WinMD version.

Tuesday, December 20, 2011

WriteableBitmapEx 1.0 Coming Soon, Test it Now!

A new version of the WriteableBitmapEx open source library has just been released, but that isn't the last release for this year. No, Andrew Burnett-Thompson and I refactored the library to make it easier portable and we added full WPF support. Andrew did most of the work since he needed the current WriteableBitmapEx library for one of his WPF projects. As a result of the refactoring, WriteableBitmapEx will have maintained support for WPF starting with version 1.0.
I'd have loved to add support for WinRT too, but unfortunately it seems that WinRT only supports streamed reading / writing of the pixel buffer at the moment. I will wait until Microsoft ships the Windows 8 beta early next year and see what they have in there. Many WriteableBitmapEx algorithms need random buffer index access and I don't want to waste my time with massive memory copying now. Who knows what else comes in the beta and it might be better to use a whole different approach for immediate rendering with Windows 8 and WinRT.

All samples were tested with the new version, but due to the massive refactoring more testing is needed. Please test the beta version with your projects and report any bugs you find. You can download the binaries here. Note that this package only contains the WriteableBitmapEx binaries for Silverlight, Windows Phone and WPF. All the samples can be found in the source code repository in the branch "WBX_1.0_BitmapContext". If all goes well this branch will become the trunk in a couple of weeks.

Monday, December 5, 2011

Windows Phone Sites Around the World

I recently released an update of my Windows Phone app Pictures Lab which brings some nice new features like effect combination, two Christmas and a New Year frame and most importantly 7 new languages. Pictures Lab 4.0 now supports 9 languages: English, German, Japanese, Russian, Dutch, French, Italian, Spanish, Portuguese. This was made possible by a group of awesome native-speaking translators: Alan Mendelevich, Takeshi Miyauchi, David Salazar, Joost van Schaik, Johan Peeters, Paolo Barone, Simone Chiaretta, Pedro Lamas and Quentin Calvez.


I also asked my translators if they know any local Windows Phone news sites / blogs. Below is a list of international and regional Windows Phone news sites we collected. Note, that those are primarily consumer sites read by consumers and not only for developers. This list could be useful if you plan to release a localized version of your app and want to promote it a bit. Most sites have a "Tip Us" or contact form and are mostly happy about new content to write posts about.

Forget this list! 
Head over to @ailon's awesome dedicated site: http://windowsphonesites.com

English
German
Russian
Japanese
Dutch
Spanish
Portuguese (Brazilian)
Italian
French
Danish

If you know more sites, please leave a comment and I'll update the list.

Telerik published a nice whitepaper with more resources about app promotion.

Friday, October 28, 2011

WriteableBitmapEx 0.9.8.5 Now Available

The WriteableBitmapEx open source library has come a long way since I created the CodePlex site in December 2009. A lot of features and the support for new platforms were added in subsequent releases. The package is also available via NuGet since this year.
The new release v0.9.8.5 was just made public. A few new features were added and many small, uncritical issues were fixed (see the list below). The binaries can be downloaded from here or via the NuGet package. Please note that this package only contains the WriteableBitmapEx binaries for Silverlight and Windows Phone. All the samples can be found in the source code repository.


Feature list version 0.9.8.5
  • Added a Rotate method for arbitrary angles (RotateFree). Provided by montago.
  • Added Nokola's anti-aliased line drawing implementation.
  • Updated the Windows Phone project to WP 7.1 Mango.
  • Added an extension code file for the Windows Phone specific extensions and added SaveToMediaLibrary extensions including support for saveToCameraRoll.
  • Added an Invert method, which creates an inverted version of the input bitmap. This is useful for WP7 Theme-awareness checks using Application.Current.Resources["PhoneBackgroundBrush"].
  • Added FromContent method, which provides an easy interface to load a WriteableBitmap from the content of the app.
  • Added a static overload for the Resize method which takes the pixels array as argument.
  • Optimized the DrawLine algorithm.
  • Fixed some issues with DrawRectangle, FillRectangle, DrawEllipse, FillEllipse and DrawPolyline.
  • Fixed a bug in the bilinear Resize method that appeared when the alpha value is zero.
  • Fixed other minor issues.

Community Community Community!
Thanks to the community for constantly reporting bugs, suggesting new features and contributing code. That's exactly why open source software is just awesome.

Tuesday, April 19, 2011

WriteableBitmapEx goes NuGet

The WriteableBitmapEx library is now available as a NuGet package. The package contains the Silverlight and the Windows Phone binaries. The sources and the PDB are also available at SymbolSource.org.
NuGet is a neat package management system for the .Net platform which makes the life of a .Net developer much easier. If you haven't tried NuGet until now, you should definitely give it a try. I'm sure you won't regret it. To install NuGet, open Visual Studio's Tools -> Extension Manager and search the Online Gallery for NuGet. You can then open a project, right click the References and select "Add Library Package Reference".

Tuesday, February 15, 2011

Long Time No See - WriteableBitmapEx 0.9.7.0

I actually wanted to release the feature complete version 1.0 of the WriteableBitmapEx library after the previous release, but I've been very busy with other projects during the last year. That's why I decided to release version 0.9.7.0 today. It contains many fixes, but also adds some features (see below). This version finally provides an official Windows Phone binary build, although the Windows Phone project was already available shortly after the first CTP was released. The zipped binaries can be downloaded from here. Please note that this package only contains the WriteableBitmapEx binaries for Silverlight and Windows Phone. All the samples can be found in the source code repository.

WPF
There's now also an unmaintained WPF branch of the WriteableBitmapEx library in the source code repository. It was contributed by Szymon Kobalczyk.
One might ask why it's not maintained. I started a poll and it seems that only 7 out of 16 need a WPF version of WriteableBitmapEx. The code is also quite bloated due to conditional compilation flags, which makes it harder to maintain in the future. That's why I decided not to integrate the WPF version. I just don't have enough time to maintain a hardly used version. I would rather point WPF users to Jeremiah Morrill's new project called DirectCanvas. It's in an early stage, but he's a great guy and working hard on it. I'm sure we'll see a great, GPU accelerated 2D drawing library for WPF in the future.

Feature list version 0.9.7.0
  • Fixed many bugs.
  • Added the Rotate method which rotates the bitmap in 90° steps clockwise and returns a new rotated WriteableBitmap.
  • Added a Flip method with support for FlipMode.Vertical and FlipMode.Horizontal.
  • Added a new Filter extension file with a convolution method and some kernel templates (Gaussian, Sharpen).
  • Added the GetBrightness method, which returns the brightness / luminance of the pixel at the x, y coordinate as byte.
  • Added the ColorKeying BlendMode.
  • Added boundary checks to the Crop() function to avoid OutOfRangeExceptions if the passed parameters are outside the boundaries of the original bitmap.
  • Optimized the DrawLine algorithm.
  • Optimized the Resize algorithms (NearestNeighbor is now 10x faster).
  • Optimized the Clear(Color) method.

Community FTW!
Thanks to the community for constantly reporting bugs and suggesting new features. You rock! That's why I love open source software.

Monday, January 24, 2011

Kostenloser Windows Phone Artikel in der DotNetPro

I've written a Windows Phone development article for Germany's largest .Net developer magazine. It's written in German.

Für die aktuelle DotNetPro habe ich einen Artikel zu der Entwicklung für Windows Phone 7 geschrieben. Anhand eines praktischen Beispiels werden die einzelnen APIs und Tricks gezeigt um eine Windows Phone App für die einfache Bildmanipulation zu entwickeln.
Als Werbung für das aktuelle Magazin wird der Artikel auch kostenlos online zur Verfügung gestellt. In der Druckausgabe findet man neben meinem Artikel auch andere Windows Phone Artikel. Wer noch tiefer in die Windows Phone Entwicklung einsteigen möchte, dem sei auch das Buch von Patrick Getzmann, Simon Hackfort, und Peter Nowak empfohlen: Entwickeln für Windows Phone 7: Architektur, Frameworks, APIs.


Thursday, December 9, 2010

Issue with the WP7 PictureDecoder and Workaround

This is fixed in the WP 7.1 SDK /  WP 7.5 / Mango!
I noticed a strange behavior of the Windows Phone PictureDecoder DecodeJpeg method while I was working on my Pictures Lab app.
This short post describes the issue I encountered and also provides a workaround.
The built-in DecodeJpeg method decodes a JPEG image stream into a WriteableBitmap. The method has two overloads, where the first only takes the JPEG stream and the second also uses parameters for the maximum width and height of the output. I encountered a strange behavior of the latter method.

Issue
The DecodeJpeg method with 3 parameters swaps the width and the height parameters when a landscape photo should be resized. For example, an image with the original size of 3264 x 2448 should be decoded to a WriteableBitmap and resized to 1024 x 768. But the resulting output will have a size of 768 x 576 cause the method swapped the input parameters while preserving the correct aspect ratio.
Please note that this only happens with landscape pictures, which means the width of the image is greater than the height.

Will it get fixed?
Yes! I contacted Microsoft and they confirmed this issue and said that it will get fixed in a future version of the Windows Phone Silverlight runtime.

Workaround
Isolating the cause of this strange behavior took a bit of time, fortunately the easier was the obvious workaround.

int w = desiredOutputWidth;
int h = desiredOutputHeight;

// Workaround for issue in DecodeJpeg method:
// Swap width and height for landscape pictures.
if (originalWidth > originalHeight)
{
   w ^= h;
   h ^= w;
   w ^= h;
}
var writeableBitmap = PictureDecoder.DecodeJpeg(jpegStream, w, h);
The code tests if the original width is greater than the height and then swaps the output width and height using the good old XOR swap trick.
Alternatively you can avoid the DecodeJpeg overload with the resizing functionality, decode the full sized image and use the WriteableBitmapEx Resize method afterwards. It produces similar results when bilinear interpolation is used, but it's an extra step that costs resources.

The above photo was taken with a HTC Mozart and edited with Pictures Lab (cropped, rotated and 1989 vintage effect).

Monday, October 18, 2010

Pictures Lab for Windows Phone

"Windows Phones are going to be absolutely amazing devices for taking pictures and dealing with pictures." - Joe Belfiore at the official Windows Phone 7 launch event in NYC. I totally agree, they are. Just think about that each device needs to have at least a 5 megapixel camera and the little camera button with the "pocket to picture" functionality. I've been working heavily to enhance this photo experience with my kind of skills. This blog post contains information about the Windows Phone app I created and will also provide the references to how it works internally.


Download here

Pictures Lab is the ultimate picture effects app for all Windows Phone device types.
MSNBC.com: "a Swiss Army knife of photo tweaks".
Engadget.com: "a must-have for WP7 devices ... the program provides a set of amazing effects and tweaks for your photos"
Gizmodo.com : "Pictures Lab offers a ton of effects for your money."

If you like to make beautiful photos, then this app is a perfect addition to your phone’s toolset. Pictures Lab provides you with thousands of different modifications for your photos and has a camera functionality with superior features like face detection auto focus, steady mode and much more. It's also integrated as a Lens.
Pictures Lab is the original with high quality filters, features and great user experience. It's fast and responsive and you quickly get your job done with just a few moves. Often been copied, but never reached.
Microsoft uses Pictures Lab in its presentations as a "delightful app" which "Looks and feels like an integral part of Windows Phone". "Uncluttered, polished experience".

The app comes with controllable, easy-to-use, but advanced effects like different vintage and hipster-like filters, Tilt Shift (miniature faking), HDR, Lomo, Soften, Auto Adjust, Sharpen, Comic, Bulge, B&W, Sepia and many more. Dynamic previews of the effects are shown in a list, making it possible to easily pick the right one. The high quality borders are also presented in a nice preview list and can be combined with any filter and any aspect ratio. Multiple effects can also be combined.
It is also possible to crop, rotate and flip images. An enhanced picture and the EXIF data can be saved to the phone’s pictures hub or shared directly on Facebook, Twitter and other social networks. Later editing is also supported. The app performs the image processing on the original picture in its original resolution, thus making it also possible to print the image or use it as desktop wallpaper.
Full Pictures Hub Apps integration and support for landscape and portrait orientation. Trial version with complete functionality only save is disabled.

    If YouTube works better for you.

Reviews
  • The well-known site Engadget lists it under The best apps, accessories, and tips. They write: "... a must-have for WP7 devices ... the program provides a set of amazing effects and tweaks for your photos ..."
  • Gizmodo included Pictures Lab in Windows Phone 7 Essential Apps, Reviewed. They also recorded a video. They write: "Your phone isn't complete until you can take photos that look like they came out of a $5 camera from 1974. Pictures Lab fortunately offers a ton of other effects for your money. $2."
  • Gizmodo Australia also featured it in the article The Best Windows Phone 7 Apps.
  • msnbc.com wrote: "The app, a Swiss Army knife of photo tweaks, will be one of my first downloads."
  • techradar.com wrote that Pictures Lab is the #1 app worth paying for: "Tilt-shift effects, crop and rotate... Pictures Lab combines the fun effects of an iPhone photo app like Hipstamatic with the useful fixes you're mostly likely to need (sharpen and - in the imminent update - crop) in a beautifully designed app that crosses the power of Silverlight with the tools of the Windows Phone 7 interface. Pick a photo, see all the possible effects as thumbnails or swipe up and down to try them one at a time."
  • msnbc.com listed it in the article: "The first Windows Phone 7 apps you should grab"
  • MSN UK listed it under the "20 top mobile phone app". And they put my fat nose on the front page. Fortunately two of my girls brought the beauty back to the page.
  • America's popular WIRED magazine with a circulation of 800,000 featured Pictures Lab in there special edition WIRED App Guide.
  • UK's popular gadget magazine T3 with a circulation of more than 60,000 featured Pictures Lab in the 02/2011 issue on the page: "Killer Apps"
  • Pictures Lab was featured in Channel 9's Hot Apps series.
  • Nokia writes "it’s the closest thing to having Photoshop on your mobile phone."
  • Nokia included Pictures Lab in Top of the Apps: 10 Hotties.
  • Softpedia featured the Windows Phone 8 update.
  • All About Windows Phone reviewed the app: "Pictures Lab is one of many photo toolboxes for your smartphone, but it's the one that I enjoy using the most." and "Very, very much recommended."
  • All About Windows Phone also reviewed the Windows Phone 8 update: "It goes significantly beyond the one shot filters typically offered in apps of this type (Nokia Creative Suite, HTC Photo Enhancer) to the point at which it's about a lot more than just fun filters."
  • Another very popular UK magazine Stuff wrote a 5 stars review in the March edition. They write that Pictures Lab is better than a well-known iPhone app.  
  • Germany's popular media and design magazine PAGE with a circulation of 20,000 featured Pictures Lab in the 01/2011 issue
  • Microsoft features Pictures Lab in their presentation slides for Windows Phone under the category delight: "Looks and feels like an integral part of Windows Phone 7". "Uncluttered, polished experience".
  • Geek.com listed it as one of the Five must have apps for Windows Phone: "Pictures Lab is $2.99, but well worth it in my opinion for all of the new features added to the camera on your phone."
  • The famous blogger Scott Hanselman says in his Essential Apps blog post: "Pictures Lab is a nice effects and editing application (if not THE BEST editing app) for Windows Phone. All the functionality is there and cleanly integrated with the Photos Hub. Crop, Rotate, Effects, etc. It's a must-have if you are doing any photography on your phone."
  • Business Insider writes "Pictures Lab is like Instagram for Windows Phone 7. Take pictures with Pictures Lab, apply filters, and share them with friends."
  • The famous design site Smashing Magazine included Pictures Lab as an example in the article Introduction To Designing For Windows Phone 7 And Metro
  • Bright Hub lists Pictures Lab as the first app in Top 5 Samsung Focus Apps: "It is considered one of the most popular photo editing programs on the Windows Phone platform, and for good reason. It has an array of sophisticated and beautiful effects ..."
  • APC (Australian Personal Computer) writes: "WP7’s best picture editing and effects app.Pictures Lab has received a lot of attention as the “go-to” image editing suite for new WP7 users – and for good reason, too."
  • Mobility Digest wrote: "This app makes me happy. Tons of features, seems simple to use and it’s cheap – that’s a win! It even has a trial mode that includes all effects."
  • Mobility Digest also posted a walk through: "I didn’t realize it, but when you go to the list of available effects you get to see a preview of the effect which is really great and I have to say, I’m really impressed for how much this app can do."
  • Mobility Digest listed it in: "The First 25 Windows Phone Apps To Download"
  • Pocket-Lint wrote in the article Best Windows Phone 7 photography apps: "... the smart way to go is with Pictures Lab..."
  • maximumpc.com wrote: "Speaking of pictures, for two bucks you can have a great little mobile suite of photo effects, fixes, and basic editing tools. The Windows Phone 7 UI language really shines through in this one."
  • Mobile Choices listed it as one of the two Windows Phone apps in The 12 best Christmas apps: "...turning lifeless images into photographic masterpieces..."
  • The blog Noisecast recorded a nice video review: "The program @PicturesLab is the best photo editor for Windows Phone 7, hands down."
  • 1800pocketpc.com wrote: "If you love to add effects to your picture then this is one app video you wouldn’t want to miss."
  • 1800pocketpc.com also wrote a review including a video
  • wpcentral.com wrote: "... interesting photo effect application."
  • wpcentral.com also got the WP8 update and : "... Things fly along nicely and the effects don’t take too long to apply in full ..."
  • mobiledownloadblog.com wrote: "There is no doubt that any phone device is incomplete without good picture depiction. A fantastic photograph app known as Picture Lab is now available for Windows Phone 7."
  • Techland.com has it on the list: "50 Windows Phone 7 Apps to Get You Started"
  • mobiledownloadblog.com has it on the list: "Samsung Focus: 30 Best WP7 Applications"
  • The German site phoneseven.de wrote: "Die App sieht wirklich klasse aus und lässt sich allem Anschein nach wirklich gut bedienen. Wer also befürchtet hat, dass Windows® Phone 7 zu wenig Möglichkeiten für gute Apps bietet, der wird mit Pictures Lab sicherlich eines besseren belehrt. Die App wird sicherlich zu meinen ersten Käufen aus dem Marketplace gehören."
  • The Portuguese site pcdebolso.com also wrote an article: "Pictures Lab a caminho do Windows phone 7"
  • Dave Campbell wrote a nice review: "All-in-all, I give Pictures Lab 5 stars"
  • John Papa wrote: "Overall, very nice app, good UI, snappy (which was a surprise to me since it does a lot)."
Feature list
  • Full support for Windows Phone 7 and 8 including all screen resolutions.
  • 30 advanced effects: Ten different vintage and hipster-like effects, Tilt Shift (miniature faking), HDR, Lomo, Soften, Auto Adjust, Sharpen, Comic, Bulge, B& W, Sepia, Manual, Edge Detection, Night Vision, Rainbow, Mirror, X-Ray, Heat Image, Colorization, Negative and Bitmap.
  • Editable effect parameters with ready-to-use default values.
  • Combination of multiple effects.
  • 11 high quality borders and more seasonal borders.
  • Share on Facebook, Twitter, Email, NFC and much more.
  • Take photo functionality with face detection auto focus, steady mode, rule of thirds grid. Integrated into the phone as a Lens. The steady mode requires a device with a gyroscope. The face focus is enabled if the device supports focus at point. It also supports devices with a front facing camera.
  • Post edits from the Pictures Hub using the WP Rich Media extension.
  • Crop, rotate and flip also with predefined aspect ratios.
  • Multi-touch manipulation for Tilt Shift and other effects where multi-touch is meaningful.
  • The app can save edited pictures with advanced effects applied in full resolution even on a device with 256 MB RAM. Thus making it also possible to print the image or use it as desktop wallpaper.
  • Full Pictures Hub Extras integration.
  • The trial version includes the complete functionality and all the effects, only the save functionality is disabled.
  • Support for landscape and portrait orientation.
  • Effect list with dynamic previews and caching of the larger previews.
  • Flicking through the effects on the main page.
  • Setting for the maximum output size, JPEG quality and many more.
  • State preservation when the app is deactivated (tombstoning).
  • Localization for English, German, Japanese, Chinese, Russian, Dutch, French, Italian, Spanish, Portuguese and Portuguese (Brasil).








How it works
Some of the image processing algorithms that are used in the Pictures Lab app would normally be implemented as pixel shaders for Silverlight. The Windows Phone platform doesn't support custom pixel shaders at the moment, therefore all effects are implemented in C# and manipulate the WriteabeBitmap Pixels' in some way. How this works in detail was shown in my Coding4Fun articles I've written months ago. This is actually where Pictures Lab has its roots. The first article described all the necessary basics and two simple effects. The second part of this short Coding4Fun article series shows how to implement the basic tilt shift and vintage effects you can find in the Pictures Lab app. Yes, some parts are open source! Except the secret sauces I gotta keep for me that adds the final touch to the effects. I also wrote blog posts about some parts of the application that are surely interesting for other Windows Phone developers.
The Slider control that is used in the App was originally developed by Nokola and then adapted for Windows Phone and made bindable by Clint Rutkas and myself.

To be continued
The planned feature list for the next versions is already pretty long and I have some real diamonds on there. You can follow @PicturesLab on Twitter to get all the status updates. I'd also like to know what feature you want to see in a future version. Just write a comment.

Tuesday, August 10, 2010

Coding4Fun - Part 1 of the Windows Phone Picture Effects App and Roadmap

My new Windows Phone 7 article for Microsoft's Coding4Fun site is live. It's the first part of a short series about the development of a Windows Phone 7 picture effects application called "PicFx". The first article will show how to create the base Windows Phone application and how to implement some basic effects. The source code is licensed under the Ms-PL and can be downloaded from the CodePlex site.
I'm already working on the second part of the series, which will explain how to implement advanced effects (the cool stuff) and other features. After this article I'll add more features and important effects, enhance the existing effects and release it as "Pictures Lab" on the Marketplace.

Video
The video below demonstrates the Coding4Fun PicFx application features and also shows how it can be used. It was recorded with the application running in the emulator.

Monday, July 19, 2010

Photos, Photos, Photos - How To Save, Load And Iterate Pictures With Windows Phone 7

The Windows Phone developer tools beta version was recently released and brought some important changes and also new features. For example the emulator is a lot better now and tombstoning was introduced. Tombstoning is an important concept to know when a Launcher or Chooser is being used in an app.
But this blog post is not about tombstoning, this post will show how to load an image from the picture library with the PhotoChooserTask. And most important how to save a picture to the library, which is not as obvious as the usage of the Task API. The last part will show how to get all images from the picture library without using the PhotoChooserTask.

Sample
I've built a Windows Phone 7 app that uses the WriteableBitmapEx library and lets the user draw on the WriteableBitmap surface. The app supports multi touch for drawing and the radius of the pen can be changed with the Slider control. An image from the phone's picture library can be chosen with the folder icon button and the floppy disk button saves the current image to the picture library. When the third button (download icon) is clicked, all pictures from the phone's library are loaded without further user interaction. The trash button clears the draw surface.
The video below demonstrates the features and shows how to use the app.
It would be great if anyone could try this sample app on a real device and give me some feedback. I'm especially interested how the multi touch drawing works.


Background music is Soft Shapes by Planet Boelex.

How it works
The raw touch points are handled through the Touch.FrameReported event. For each multi touch point a circle is being drawn with the WriteableBitmapEx' FillEllipseCentered method and a color map array that provides alternating colors:
private void Draw(IList<TouchPoint> points)
{
   // Check
   if (!isManipulating)
   {
      return;
   }

   // Init some vars
   var bmp = Bitmap;
   var w = bmp.PixelWidth;
   var h = bmp.PixelHeight;
   var r = Radius;

   // Draw
   for (int i = 0; i < points.Count; i++)
   {
      var p = points[i].Position;
      if (p.X < w && p.Y < h)
      {
         bmp.FillEllipseCentered((int)p.X, (int)p.Y, r, r, 
                                 ColorMap[(i + colorBase) % ColorMap.Length]);
      }
   }

   // Show
   Present();
}


Choose a photo
The PhotoChooserTask allows the user to select an image. The code for this task is pretty straight forward with the beta of the developer tools.
A member variable of the PhotoChooserTask is instantiated in the constructor and an event handler for the Completed event is attached.
public MainPage()
{
   // ...

   // Init chooser
   photoChooserTask = new PhotoChooserTask();
   photoChooserTask.Completed += PhotoChooserTaskCompleted;
   
   // ...
}
private void PhotoChooserTaskCompleted(object sender, PhotoResult e)
{
   if (e.TaskResult == TaskResult.OK)
   {
      // Load original image and invalidate bitmap so it gets newly rendered
      var bitmapImage = new BitmapImage();
      bitmapImage.SetSource(e.ChosenPhoto);
      Viewport.Source = bitmapImage;
      bitmap = null;
   }
}

The PhotoChooserTask.Show method is called when the corresponding Application Bar button was clicked:
private void ApplicationBarIconOpenButton_Click(object sender, EventArgs e)
{
   photoChooserTask.Show();
}

The Show method launches the Windows Phone photo app. The current version of the Windows Phone operating system only allows one application to run at the same time and therefore our app gets terminated when the Chooser is started. Here's where the concept of tombstoning comes into play.
After the user selected an image or pressed the back button, the Chooser's Completed event is raised. You might have noticed the black screen in the video that appears after the choose operation. As a result of the app termination, the Visual Studio debugging session is stopped. The Windows Phone 7 emulator detected that the app was started in a debug context and the emulator now waits at the black screen for re-attaching. So just go back to Visual Studio and hit F5 (Start Debugging), then the debugger is being re-attached and the app continues. Of course it's also possible to Start Without Debugging in Visual Studio.
The Chooser's Completed event provides a PhotoResult that contains the TaskResult, the OriginalFileName and the ChosenPhoto as a Stream. If the user hasn't cancelled the operation, the stream is used as the source of a BitmapImage which is then assigned to the WriteableBitmap draw surface (Viewport). The user can now make some nice drawings on the photo.


Save a picture
After the user created his masterpiece he probably wants to save it back to the picture library / photo album. But how could this be done? There's no PhotoSaveTask available in the Silverlight SDK. Fortunately the Windows Phone's XNA MediaLibrary comes to the rescue. Only a reference to the Microsoft.Xna.Framework assembly is needed to use it in our Windows Phone Silverlight application. To make this task a bit easier I wrote some reusable extension methods for the WriteableBitmap. These are located in the file WriteableBitmapMediaLibraryExtensions.cs from the source code download. The signatures look like this:
// Saves the WriteableBitmap encoded as JPEG to the Media library.
// The quality for JPEG encoding has to be in the range 0-100, 
// where 100 is the best quality with the largest size.
void SaveToMediaLibrary(this WriteableBitmap bitmap, string name, int quality);

// Saves the WriteableBitmap encoded as JPEG to the Media library 
// using the best quality of 100.
void SaveToMediaLibrary(this WriteableBitmap bitmap, string name);

The methods use the MediaLibrary's SavePicture method internally. The SavePicture method expects a stream or a byte array as parameter that contains an image encoded in the JPEG format. For the earlier CTP versions I wrote a custom JEPG encoding functionality that used some parts of my Silverlight JPEG encoding blog post and an adapted FJCore version. Fortunately things got a bit easier with the Windows Phone Tools beta release. The Microsoft.Phone assembly now comes with two WriteableBitmap extension methods called LoadJpeg and most important SaveJpeg. The SaveJpeg method expects the targetStream, the width and height of the target, the orientation which is not used at the moment and the quality in a range from 0 to 100. The width and height parameters are useful when a scaled version of the WriteableBitmap should be saved as JPEG.

The current bitmap surface is saved as JPEG when the disk floppy button was clicked:
private void ApplicationBarIconSaveButton_Click(object sender, EventArgs e)
{
   var name = String.Format("MediaLibSample_{0:yyyy-MM-dd_hh-mm-ss-tt}.jpg",
                            DateTime.Now);
   Bitmap.SaveToMediaLibrary(name);
}


Load all pictures
The last thing I'd like to cover in this post is the Pictures property of the MediaLibrary class. This property returns a collection of Picture instances. This class provides all the necessary meta information about the picture and streams of the image and thumbnail data.
I use this in the sample code to create a mosaic of all Windows Phone media library pictures:
private void ApplicationBarIconOpenAllButton_Click(object sender, EventArgs e)
{
   using(var mediaLib = new MediaLibrary())
   {
      // Pictures also includes saved pics, 
      // mediaLib.SavedPictures returns the same collection items
      var allPics = mediaLib.Pictures;

      // Combine the pics to a single WriteableBitmap mosaic
      var bmp = Bitmap;
      bmp.Clear();
      int x = 0;
      int y = 0;
      foreach (var picture in allPics)
      {
         // Load thumbnail stream to WriteableBitmap
         var wb = new WriteableBitmap(0, 0);
         wb.SetSource(picture.GetThumbnail());

         // Blit thumbnail to background bitmap
         var w = wb.PixelWidth;
         var h = wb.PixelHeight;
         bitmap.Blit(new Rect(x, y, w, h), wb, new Rect(0, 0, w, h));
         x += w;

         // Check bounds and move to next row
         if (x >= bitmap.PixelWidth)
         {
            x = 0;
            y += h;
         }
         // Bitmap filled
         if (y >= bitmap.PixelHeight)
         {
            break;
         }
      }
   }

   Present();
}

The GetThumbnail method returns the stream of an image thumbnail sized 99 x 99 pixels. This bitmap is then combined with the surface bitmap by using the WriteableBitmapEx' Blit method.
Beside the Pictures property the MediaLibrary also has the SavedPictures property, but I encountered that the SavedPictures collection returns all pictures in the emulator and not only saved pictures like the name and documentation implies. But as a little bird told me, the SavedPictures property works as expected on a real device.
The MediaLibrary has some more members that might become interesting in the future, esp. when combined with the MediaPlayer class.


Conclusion
This blog post covered the complete workflow of loading, manipulating and saving a picture to the Windows Phone's picture library / photo album. I also showed how to load all images from the library and mentioned some gotchas.

Source code
Download the complete Visual Studio 2010 Windows Phone solution from here.