I have used code snipped from the documentation of Lumia Imaging SDK. I have Fileopenpicker in my code and calls the viewActivated method. In this method i used the lumia imaging sdk BlurEffect code which you can find here. There are no errors but i can't get my image blurred.
Here is my full code which i used:
private void Button_Click(object sender, RoutedEventArgs e)
{
ImagePath = string.Empty;
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
filePicker.PickSingleFileAndContinue();
view.Activated += viewActivated;
}
private async void viewActivated(CoreApplicationView sender, Windows.ApplicationModel.Activation.IActivatedEventArgs args1)
{
//throw new NotImplementedException();
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
StorageFile storageFile = args.Files[0];
var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
RealImage.Source = bitmapImage;
// A blur effect is initialized with selected image stream as source.
IRandomAccessStream fileStream = await storageFile.OpenAsync(FileAccessMode.Read);
var imageStream = new RandomAccessStreamImageSource(fileStream);
using (var filterEffect = new FilterEffect(imageStream))
{
// Initialize the filter and add the filter to the FilterEffect collection
var filter = new BlurFilter(10);
filterEffect.Filters = new IFilter[] { filter };
// Create a target where the filtered image will be rendered to
var target = new WriteableBitmap(400, 400);
// Create a new renderer which outputs WriteableBitmaps
using (var renderer = new WriteableBitmapRenderer(filterEffect, target))
{
// Render the image with the filter(s)
await renderer.RenderAsync();
// Set the output image to Image control as a source
BlurredImage.Source = target;
}
}
}
}
Related
I have to save a content from Image tag to a file. I used a lot of Uncle Google but he doesn't know :(
private void QRbutton_Click(object sender, RoutedEventArgs e)
{
IBarcodeWriter writer = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new ZXing.Common.EncodingOptions
{
Height = 1200,
Width = 1200
}
};
String message = "";
if (String.IsNullOrEmpty(QRtxt.Text))
{
message = "You send empty message. ";
}
else
{
//Saving Input to string
message = QRtxt.Text;
StckPnlProfile_Layout.Visibility = Visibility.Collapsed;
QRsendbtn.Visibility = Visibility.Visible;
}
var result = writer.Write(message);
var wb = result.ToBitmap() as WriteableBitmap;
System.Diagnostics.Debug.WriteLine("BEFORE[Saving image to file]");
QRimage.Source = wb;
}
And there is XAML code of Image:
<Image x:Name="QRimage" Height="300"/>
I think your only option can be using RenderTargetBitmap class , it captures an image from any UIElement inherited class type like Image.
https://msdn.microsoft.com/library/windows/apps/xaml/windows.ui.xaml.media.imaging.rendertargetbitmap.aspx
HesamM, thank you for your response. Actually I did it in this way:
private async void saveImage(object sender, RoutedEventArgs e)
{
Debug.WriteLine("********** Function STARTED: Save QR code as image to jpg **********");
try
{
System.Diagnostics.Debug.WriteLine("Searching for assets folder.");
var package = Windows.ApplicationModel.Package.Current.InstalledLocation;
StorageFolder localFolder = await package.GetFolderAsync("Assets");
StorageFile file = await localFolder.CreateFileAsync("savedimage.jpg", CreationCollisionOption.ReplaceExisting);
var renderTargetBitmap = new RenderTargetBitmap();
System.Diagnostics.Debug.WriteLine("Rendering an image.");
await renderTargetBitmap.RenderAsync(QRimage);
var pixels = await renderTargetBitmap.GetPixelsAsync();
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
System.Diagnostics.Debug.WriteLine("Save QR code to jpg.");
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);
byte[] bytes = pixels.ToArray();
encoder.SetPixelData(
BitmapPixelFormat.Bgra8,
BitmapAlphaMode.Straight,
(uint)renderTargetBitmap.PixelWidth,
(uint)renderTargetBitmap.PixelHeight,
DisplayInformation.GetForCurrentView().LogicalDpi,
DisplayInformation.GetForCurrentView().LogicalDpi,
bytes);
await encoder.FlushAsync();
}
MessageDialog SuccessMsg = new MessageDialog("Code QR saved.");
await SuccessMsg.ShowAsync();
}
catch (Exception ex)
{
//MessageDialog ErrMsg = new MessageDialog("Error Ocuured!");
System.Diagnostics.Debug.WriteLine("ERROR ZAPISU PLIKU: " + ex);
}
Debug.WriteLine("********** Function STOPPED: Save QR code as image to jpg **********");
}
I need to copy an image from my windows universal app, I was able to pick an image from my gallery but i don't how to copy it in another folder.
Although I was able to display the image in my UWP interface, so I think that I succeed to get it as a stream.
Any help would be appreciated, I'm lost here ... here is the code I used:
public MainPage()
{
this.InitializeComponent();
// Scenario4WriteableBitmap = new WriteableBitmap((int)Scenario4ImageContainer.Width, (int)Scenario4ImageContainer.Height);
Scenario2DecodePixelHeight.Text = "100";
Scenario2DecodePixelWidth.Text = "100";
}
private async void buttonUpload_Click(object sender, RoutedEventArgs e)
{
int decodePixelHeight=150;
int decodePixelWidth=150;
// Try to parse an integer from the given text. If invalid, default to 100px
if (!int.TryParse(Scenario2DecodePixelHeight.Text, out decodePixelHeight))
{
Scenario2DecodePixelHeight.Text = "100";
decodePixelHeight = 100;
}
// Try to parse an integer from the given text. If invalid, default to 100px
if (!int.TryParse(Scenario2DecodePixelWidth.Text, out decodePixelWidth))
{
Scenario2DecodePixelWidth.Text = "100";
decodePixelWidth = 100;
}
FileOpenPicker open = new FileOpenPicker();
open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
open.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
open.FileTypeFilter.Clear();
open.FileTypeFilter.Add(".bmp");
open.FileTypeFilter.Add(".png");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".jpg");
// Open a stream for the selected file
StorageFile file = await open.PickSingleFileAsync();
// Ensure a file was selected
if (file != null)
{
// Ensure the stream is disposed once the image is loaded
using (IRandomAccessStream fileStream = await file.OpenAsync(FileAccessMode.Read))
{
// Set the image source to the selected bitmap
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.DecodePixelHeight = decodePixelHeight;
bitmapImage.DecodePixelWidth = decodePixelWidth;
await bitmapImage.SetSourceAsync(fileStream);
Scenario2Image.Source = bitmapImage;
}
}
}
private async void submit_Click(object sender, RoutedEventArgs e)
{
String url = "http://localhost/mydatabase/add.php";
var values = new List<KeyValuePair<String, String>>
{
new KeyValuePair<string, string>("UserName",UserName.Text),
new KeyValuePair<string, string>("UserImage",UserImage.Text),
};
HttpClient client = new HttpClient();
HttpResponseMessage response = new HttpResponseMessage();
try
{
response = await client.PostAsync(url, new FormUrlEncodedContent(values));
/*client.DefaultRequestHeaders.Add("content_type", "binary/octet_stream");
responseImage = client.PostAsync("", FileChooser.FileName);*/
if (response.IsSuccessStatusCode)
{
Debug.WriteLine(response.StatusCode.ToString());
var dialog = new MessageDialog("added succesfully ");
await dialog.ShowAsync();
}
else
{
// problems handling here
string msg = response.IsSuccessStatusCode.ToString();
throw new Exception(msg);
}
}
catch (Exception exc)
{
// .. and understanding the error here
Debug.WriteLine(exc.ToString());
}
}
`
you can use CopyAsync of StorageFile to copy the file you get from FileOpenPicker to a specific folder.
I'm having a little trouble developing my app. What I'm trying to do now is that let the user pick their picture from gallery(picture album) and display it. Furthermore, I want to convert that picture taken to Base64 string. Right now I've successfully pull and display picture from gallery, is there anyway I can convert that picture to base64 string.
Here's the code how I grab and display
private void picprofile_Tapped(object sender, TappedRoutedEventArgs e)
{
CoreApplicationView view;
String ImagePath;
view = CoreApplication.GetCurrentView();
ImagePath = string.Empty;
FileOpenPicker filePicker = new FileOpenPicker();
filePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
filePicker.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
filePicker.FileTypeFilter.Clear();
filePicker.FileTypeFilter.Add(".bmp");
filePicker.FileTypeFilter.Add(".png");
filePicker.FileTypeFilter.Add(".jpeg");
filePicker.FileTypeFilter.Add(".jpg");
filePicker.PickSingleFileAndContinue();
view.Activated += viewActivated;
}
private async void viewActivated(CoreApplicationView sender, IActivatedEventArgs args1)
{
CoreApplicationView view;
view = CoreApplication.GetCurrentView();
FileOpenPickerContinuationEventArgs args = args1 as FileOpenPickerContinuationEventArgs;
if (args != null)
{
if (args.Files.Count == 0) return;
view.Activated -= viewActivated;
StorageFile storageFile = args.Files[0];
var stream = await storageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
var bitmapImage = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
await bitmapImage.SetSourceAsync(stream);
var decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);
picprofile.ImageSource = bitmapImage;
}
}
See this code below help . I hope there are multiple ways to do this . The link might help you
public async Task<string> ImageToBase64(StorageFile MyImageFile)
{
Stream ms = await MyImageFile.OpenStreamForReadAsync();
byte[] imageBytes = new byte[(int)ms.Length];
ms.Read(imageBytes, 0, (int)ms.Length);
return Convert.ToBase64String(imageBytes);
}
How to set a picked image as background of a grid dynamically, save it in app local storage and retrieve it each time app is launched?
BitmapImage BgBitmap = new BitmapImage();
Image BgImg = new Image();
private async void bgbtn_Click(object sender, RoutedEventArgs e)
{
var fop = new FileOpenPicker();
fop.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
fop.FileTypeFilter.Add(".jpg");
fop.FileTypeFilter.Add(".png");
fop.CommitButtonText = "OK";
fop.ViewMode = PickerViewMode.Thumbnail;
StorageFile file = await fop.PickSingleFileAsync();
IRandomAccessStream stream= await file.OpenAsync(FileAccessMode.ReadWrite);
await file.CopyAsync(ApplicationData.Current.LocalFolder, "BackgroundImg", NameCollisionOption.ReplaceExisting);
await BgBitmap.SetSourceAsync(stream);
BgImg.Source = BgBitmap;
}
Now, how to set this BgImg as "mainGrid" Grid Background?
and it will be nice if i can save the picked file in app storage and set tht file as background.
var imageBrush = new ImageBrush();
imageBrush.ImageSource = BgBitmap;
this.mainGrid.BackGround = imageBrush;
this should work for you
In my app user can set profile pic from device memory i.e tablet memory or desktop local drive and upload it to server.
I used file picker so that user can select one picture and set it as profile picture, but the problem is the picture is not sticking to Image element.
My code:
private async void filePicker()
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
String filePath = file.Path;
System.Diagnostics.Debug.WriteLine(filePath);
Uri uri = new Uri(filePath, UriKind.Relative);
profilePicture.Source = new BitmapImage(uri);
}
}
internal bool EnsureUnsnapped()
{
// FilePicker APIs will not work if the application is in a snapped state.
// If an app wants to show a FilePicker while snapped, it must attempt to unsnap first
bool unsnapped = ((ApplicationView.Value != ApplicationViewState.Snapped) || ApplicationView.TryUnsnap());
if (!unsnapped)
{
//NotifyUser("Cannot unsnap the sample.", NotifyType.StatusMessage);
}
return unsnapped;
}
the file path that I'm getting is this one
filePath=C:\Users\Prateek\Pictures\IMG_0137.JPG
I don't know what went wrong.
I am not sure if this will solve the problem, this is what I did to set my image source.
Using a bitmap image as the source to your image
BitmapImage bitmapimage = new BitmapImage();
StorageFile file = await openPicker.PickSingleFileAsync();
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
await bitmapimage.SetSourceAsync(stream);
profilePicture.Source = bitmapImage;
I have used this code ...
var picker = new Windows.Storage.Pickers.FileOpenPicker();
picker.ViewMode = Windows.Storage.Pickers.PickerViewMode.Thumbnail;
picker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.PicturesLibrary;
picker.FileTypeFilter.Add(".jpg");
picker.FileTypeFilter.Add(".jpeg");
picker.FileTypeFilter.Add(".png");
Windows.Storage.StorageFile file = await picker.PickSingleFileAsync();
if (file != null)
{
this.textBlock.Text =
"File Path: " + file.Path + Environment.NewLine +
"File Name: " + file.Name;
try
{
var stream = await file.OpenReadAsync();
var imageSource = new BitmapImage();
await imageSource.SetSourceAsync(stream);
this.image.Source = imageSource;
}
catch (Exception ex)
{
this.textBlock.Text = ex.ToString();
}
}
else
{
this.textBlock.Text = "Operation cancelled.";
}