Convert StorageFile to a BitmapImage in Universal Windows Apps

We have already seen how to convert a WritableBitmap to a StorageFile in Universal Windows apps.

A StorageFile can be converted to a BitmapImage using the following function.

public class ImageUtils
{
    public static async Task<BitmapImage> StorageFileToBitmapImage(StorageFile savedStorageFile)
    {
        using (IRandomAccessStream fileStream = await savedStorageFile.OpenAsync(Windows.Storage.FileAccessMode.Read))
        {
            BitmapImage bitmapImage = new BitmapImage();
            bitmapImage.DecodePixelHeight = 100;
            bitmapImage.DecodePixelWidth = 100;
            await bitmapImage.SetSourceAsync(fileStream);
            return bitmapImage;
        }
    }
}

To use the function call it as follows.

BitmapImage imageSource= await ImageUtils.StorageFileToBitmapImage(savedStorageFile);

convert a WritableBitmap to a StorageFile in Universal Windows apps

Converting WritableBitmap to StorageFile in Universal Windows Apps

WriteableBitmap is quite useful when an app requires image processing. It provides a BitmapSource, that can be written and manipulated. Ultimately that bitmap source is supplied to an image control of a Windows Store app. We are going to save the WritableBitmap to a StorageFile in our app.

For image encoding WinRT offers the BitmapEncoder class. For image encoding we need to select a BitmapEncoderGuid that is basically a formatted of image, such as JPEG, PNG, TIFF, and so on. It’s actually a unique identifier for each bitmap encoder.

We will first export WriteableBitmap’s pixel buffer into a byte array. Then we will initialize the bitmap encoder with a GUID and destination file stream. Finally we will set the pixel data to a bitmap encoder. Bitmap encoder’s SetPixelData(...) gets various parameters to write the pixels in various ways. Check out the method metadata given below. At last we will have the file ready.

public class ImageUtils
{
    public static async Task<StorageFile> WriteableBitmapToStorageFile(WriteableBitmap WB, FileFormat fileFormat)
    {
        string FileName = "MyFile.";
        Guid BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
        switch (fileFormat)
        {
            case FileFormat.Jpeg:
                FileName += "jpeg";
                BitmapEncoderGuid = BitmapEncoder.JpegEncoderId;
                break;
            case FileFormat.Png:
                FileName += "png";
                BitmapEncoderGuid = BitmapEncoder.PngEncoderId;
                break;
            case FileFormat.Bmp:
                FileName += "bmp";
                BitmapEncoderGuid = BitmapEncoder.BmpEncoderId;
                break;
            case FileFormat.Tiff:
                FileName += "tiff";
                BitmapEncoderGuid = BitmapEncoder.TiffEncoderId;
                break;
            case FileFormat.Gif:
                FileName += "gif";
                BitmapEncoderGuid = BitmapEncoder.GifEncoderId;
                break;
        }
        var file = await Windows.Storage.ApplicationData.Current.TemporaryFolder
    .CreateFileAsync(FileName, CreationCollisionOption.GenerateUniqueName);
        using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
        {
            BitmapEncoder encoder = await BitmapEncoder.CreateAsync(BitmapEncoderGuid, stream);
            Stream pixelStream = WB.PixelBuffer.AsStream();
            byte[] pixels = new byte[pixelStream.Length];
            await pixelStream.ReadAsync(pixels, 0, pixels.Length);
            encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Ignore,
                      (uint)WB.PixelWidth,
                      (uint)WB.PixelHeight,
                      96.0,
                      96.0,
                      pixels);
            await encoder.FlushAsync();
        }
        return file;
    }
    public enum FileFormat
    {
        Jpeg,
        Png,
        Bmp,
        Tiff,
        Gif
    }
}

Don’t forget to add the namespace System.Runtime.InteropServices.WindowsRuntime.

To use the converter call it as follows.

StorageFile savedStorageFile= await ImageUtils.WriteableBitmapToStorageFile(ImageCropper.CroppedImage, ImageUtils.FileFormat.Png);

How to Execute a Command in C# ?

This article will help you to execute a command in C#, just like we execute a command using the Windows command prompt

The code given below creates a process i.e. a command process and then invokes the command that we want to execute. The result of the command is stored in a string variable, which can then be used for further reference. The command execution can happen in two ways, synchronously and asynchronously. In the asynchronous command execution, we just invoke the command execution using a thread that runs independently.

Below is the code to execute the command synchronously:

/// <span class="code-SummaryComment"><summary></span>
/// Executes a shell command synchronously.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="command">string command</param></span>
/// <span class="code-SummaryComment"><returns>string, as output of the command.</returns></span>
public void ExecuteCommandSync(object command)
{
     try
     {
         // create the ProcessStartInfo using "cmd" as the program to be run,
         // and "/c " as the parameters.
         // Incidentally, /c tells cmd that we want it to execute the command that follows,
         // and then exit.
    System.Diagnostics.ProcessStartInfo procStartInfo =
        new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);

    // The following commands are needed to redirect the standard output.
    // This means that it will be redirected to the Process.StandardOutput StreamReader.
    procStartInfo.RedirectStandardOutput = true;
    procStartInfo.UseShellExecute = false;
    // Do not create the black window.
    procStartInfo.CreateNoWindow = true;
    // Now we create a process, assign its ProcessStartInfo and start it
    System.Diagnostics.Process proc = new System.Diagnostics.Process();
    proc.StartInfo = procStartInfo;
    proc.Start();
    // Get the output into a string
    string result = proc.StandardOutput.ReadToEnd();
    // Display the command output.
    Console.WriteLine(result);
      }
      catch (Exception objException)
      {
      // Log the exception
      }
}

The above code invokes the cmd process specifying the command to be executed. The option procStartInfo.RedirectStandardOutput is set to true, since we want the output to be redirected to the StreamReader. The procStartInfo.CreateNoWindow property is set to true, as we don’t want the standard black window to appear. This will execute the command silently.

Below is the code to execute the command asynchronously:

/// <span class="code-SummaryComment"><summary></span>
/// Execute the command Asynchronously.
/// <span class="code-SummaryComment"></summary></span>
/// <span class="code-SummaryComment"><param name="command">string command.</param></span>
public void ExecuteCommandAsync(string command)
{
   try
   {
    //Asynchronously start the Thread to process the Execute command request.
    Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
    //Make the thread as background thread.
    objThread.IsBackground = true;
    //Set the Priority of the thread.
    objThread.Priority = ThreadPriority.AboveNormal;
    //Start the thread.
    objThread.Start(command);
   }
   catch (ThreadStartException objException)
   {
    // Log the exception
   }
   catch (ThreadAbortException objException)
   {
    // Log the exception
   }
   catch (Exception objException)
   {
    // Log the exception
   }
}

If we observe carefully, the asynchronous execution of the command actually invokes the synchronous command execution method using a thread. The thread runs in the background making the command execution asynchronous in nature.

What’s the difference between String and string?

In C#, what is the difference between String and string? (note the case)

string is an alias in C# for System.String. So technically, there is no difference. It’s like int vs. System.Int32.

As far as guidelines, I think it’s generally recommended to use string any time you’re referring to an object. e.g.

string place = "world";

Likewise, I think it’s generally recommended to use String if you need to refer specifically to the class.
e.g.

string greet = String.Format("Hello {0}!", place);

Here are a few noteworthy points about both:

  • string is just an alias for System.String. The compiler will treat them identically.
  • string is a reserved word, but String is just a class name. This means that string cannot be used as a variable name by itself.
  • You can’t use String without using System; beforehand.
  • string is a type in C#. System.String is a type in the CLR.
  • You can’t use string in reflection; you must use String.

You can do more localized aliasing for types and namespaces with the using keyword. e.g.

using str = System.String;
//...
str s = "Now you've got another alias for string!";

String and Other Aliases

string is an alias for System.String. They compile to the same code, so at execution time there is no difference whatsoever. This is just one of the aliases in C#. The complete list is:

object:  System.Object
string:  System.String
bool:    System.Boolean
byte:    System.Byte
sbyte:   System.SByte
short:   System.Int16
ushort:  System.UInt16
int:     System.Int32
uint:    System.UInt32
long:    System.Int64
ulong:   System.UInt64
float:   System.Single
double:  System.Double
decimal: System.Decimal
char:    System.Char

How to Fix IpOverUsbSvc error while registering Windows Phone device

Sometimes while registering your Windows Phone device for development you might get a IpOverUsbSvc error.

Here’s how to register your device for development.

http://windowsapptutorials.com/windows-phone/general/developer-unlock-your-windows-phone-8-device/

A simple fix that seems to work most of the times is to restart the service. Here’s how to do it.

Step 1: Open Powershell in Admin mode

Go to start and search for Powershell. Open it in Administrator mode by right clicking.

powershell

Step 2: Run the commands to restart the service

Run the following commands to restart the IpOverUsbSvc service.

IPOverUsbSvc

 

Convert Storage File to Byte Array in Universal Windows apps

This async function converts a storage file to a byte array.

public static async Task<byte[]> GetBytesAsync(StorageFile file)
{
    byte[] fileBytes = null;
    if (file == null) return null;
    using (var stream = await file.OpenReadAsync())
    {
        fileBytes = new byte[stream.Size];
        using (var reader = new DataReader(stream))
        {
            await reader.LoadAsync((uint)stream.Size);
            reader.ReadBytes(fileBytes);
        }
    }
    return fileBytes;
}

It accepts a StorageFile as argument and returns a byte array for it.