Blur images in Windows Runtime C# using WriteableBitmapEx - windows-phone-8

I am trying to blur an image in my new Windows Phone Runtime C# app (WPRT)
I used WriteableBitmapEx NuGet and this code to make my image blured but can't see any changes in my picture . what's going wrong guys ?
public TestXaml()
{
this.InitializeComponent();
....
test();
}
async void test()
{
var ImgFile = await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/TestBG.jpg"));
var wb = new WriteableBitmap(100,100);
using (var strm = await ImgFile.OpenReadAsync())
{
wb = await wb.FromStream(strm);
}
var wb3 = WriteableBitmapExtensions.Convolute(wb, WriteableBitmapExtensions.KernelGaussianBlur5x5);
ImageBrush ib = new ImageBrush();
ib.ImageSource = wb3;
PageBackground.Background = ib;
}
also I tried WriteableBitmapExtensions.KernelGaussianBlur3x3 but still no change

Related

Why is my WinRT app closing when trying to debug my background task?

I am trying to experiment with downloading files on a regular basis with background tasks for windows store applications, and am having trouble.
I followed the sample at https://msdn.microsoft.com/en-us/library/windows/apps/xaml/hh977055.aspx, and even downloaded/ran it and everything worked perfectly (including being able to step into the timer background task).
So with that I created my own background task in a brand new Windows namespace
Win8BackgroundTest
{
public class TestBackgroundTask
{
public async void Run(IBackgroundTaskInstance taskInstance)
{
var deferral = taskInstance.GetDeferral();
var uri = new Uri("http://download.blender.org/peach/bigbuckbunny_movies/big_buck_bunny_480p_h264.mov");
var folder = ApplicationData.Current.LocalFolder;
var downloadFile = await folder.CreateFileAsync(uri.Segments.Last(), CreationCollisionOption.GenerateUniqueName);
var dataFile = await folder.CreateFileAsync("downloadData", CreationCollisionOption.GenerateUniqueName);
var downloader = new BackgroundDownloader();
var operation = downloader.CreateDownload(uri, downloadFile);
await FileIO.WriteTextAsync(dataFile, "Success at " + DateTime.Now);
deferral.Complete();
}
public static async void RegisterTask()
{
const string taskName = "TestBackgroundTask";
try
{
var status = await BackgroundExecutionManager.RequestAccessAsync();
if (status == BackgroundAccessStatus.Denied)
{
return;
}
}
catch
{
// already accepted
}
var tasks = BackgroundTaskRegistration.AllTasks
.Where(x => x.Value.Name == taskName)
.ToArray();
if (tasks.Any())
{
return;
}
var builder = new BackgroundTaskBuilder
{
Name = taskName,
TaskEntryPoint = "Win8BackgroundTest.TestBackgroundTask",
};
builder.SetTrigger(new TimeTrigger(60, false));
var registeredTask = builder.Register();
}
}
}
I set up the application's manifest with a Background Tasks declaration, checking the Timer properties checkbox, and set the EntryPoint to Win8BackgroundTest.TestBackgroundTask.
I then added the following at the end of my App.xaml.cs's OnLaunched() method:
TestBackgroundTask.RegisterTask();
Stepping through seems to have task registration work successfully with no exceptions. I then go back to visual studio, added a breakpoint to the first line in my task's Run() method, I then go to the debug locations toolbar, click the down arrow and select TestBackgroundTask. A few seconds later visual studio exits (as does my app).
Does anyone see what I am doing wrong that is causing background tasks to fail?
So after much frustration and a lot of trial and error the issue was a combination of both of the comments.
So first of all, it appears like you cannot have a background task in the same project as the rest of your windows store application. It must be in it's own windows runtime component project.
Finally, there are times where it just doesn't work and for whatever reason deleting the bin and obj folders fix it.

WindowsPhone MediaTranscoder with MediaStreamSource

I'm trying to create a Video with an Image using MediaTranscoder class in WindowsPhone 8.1 SDK. If I succeed I would then use it to create a video with more images.
in the code below I find an image inside the pictures library and create a MediaStreamSample from it. this works fine!
then I create a MediaStreamSource with duration of 1 (Sec) and relate it to the sample I Created before. this works fine too!
What doesn't work is the MediaTranscoder instance.
await transcoder.PrepareMediaStreamSourceTranscodeAsync(src, ras, profile);
when I call the above method I get a "Reference not set to an instance" exception. (null Reference exception)
I don't know why this happens... please help me.
StorageFolder cameraFolder = KnownFolders.CameraRoll;
IReadOnlyList<StorageFile> fileList = await cameraFolder.GetFilesAsync();
var query = fileList.Where(f => f.Name.StartsWith("JeyLapse")).ToList();
var stream = await query[0].OpenStreamForReadAsync();
MediaStreamSample sample =
await MediaStreamSample.CreateFromStreamAsync(stream.AsInputStream(), (uint)stream.Length, new TimeSpan());
MediaStreamSource src = new MediaStreamSource(new VideoStreamDescriptor(VideoEncodingProperties.CreateMpeg2()));
src.Duration = TimeSpan.FromSeconds(1);
src.SampleRequested += (sender, args) =>
{
args.Request.Sample = sample;
};
src.Starting += (sender, args) => args.Request.SetActualStartPosition(new TimeSpan());
src.SwitchStreamsRequested += (sender, args) => args.Request.GetDeferral().Complete();
MediaTranscoder transcoder = new MediaTranscoder();
MediaEncodingProfile profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Auto);
var newFile = await KnownFolders.VideosLibrary.CreateFileAsync("tryJeylapse", CreationCollisionOption.GenerateUniqueName);
var writestr = await newFile.OpenStreamForWriteAsync();
var ras = writestr.AsRandomAccessStream();
transcoder.VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.Default;
var trans = await transcoder.PrepareMediaStreamSourceTranscodeAsync(src, ras, profile);
await trans.TranscodeAsync();

Refresh an ObservableCollection when Item's property changed

I have a observableCollection which is loaded with elements and displayed on the UI .At the same time the app is downloading one Icon for each element of the observable collection.I would like to display each Icon when its download finishes...
My code is working but i guess it's not the best pratice because I bind my collection to the Ui control 2 times...I am pretty convinced that it shouldn't be necessary ...I try to implement the InotifypropertyChanged on the element's Icon property but I still have to add those lines of code to display the Icons:
listDocsLibs = new ObservableCollection<BdeskDocLib>(listBoxGetDocsLibs);
llslistDocslibs.ItemsSource = listDocsLibs;
Below the function which dowload the Icons
List<BdeskDocLib> listBoxGetDocsLibs = new List<BdeskDocLib>();
ObservableCollection<BdeskDocLib> listDocsLibs = new ObservableCollection<BdeskDocLib>();
private async void LoadIconDocLibs()
{
foreach (var doclib in listBoxGetDocsLibs)
{
byte[] Icon = await ServerFunctions.GetDocLibsIcon(doclib);
if (Icon != null)
{
{
var ms = new MemoryStream(Icon);
BitmapImage photo = new BitmapImage();
photo.DecodePixelHeight = 64;
photo.DecodePixelWidth = 92;
photo.SetSource(ms);
doclib.Icon = photo;
}
}
else if (Icon == null)
{
doclib.Icon = new BitmapImage();
doclib.Icon.UriSource = new Uri("/Images/BDocs/ico_ext_inconnu.png", UriKind.Relative);
}
}
}
//IM PRETTY SURE The following code IS NOT NECESSARY BUT WHY MY UI IS NOT REFRESHING WITHOUT ?
listDocsLibs = new ObservableCollection<BdeskDocLib>(listBoxGetDocsLibs);
llslistDocslibs.ItemsSource = listDocsLibs;
}

http error 405 with mobile flex application

i am having an issue everytime i try to upload an image from a flex mobile application to an IIS directory and this directory is configerd to be web application
i get an HTTP error 405 'method not allowed'
hence i dont use any script from the server side and i dont want to use any ..
and the code for the upload button is
protected function getImage(event:Event):void
{
var image:Bitmap = Bitmap(event.target.content);
bitmapData = image.bitmapData;
byte = jpgEncoder.encode(bitmapData); // bytearray
uploadrequest = new URLRequest("http://localhost/ProblmeImages/");
var header:URLRequestHeader = new URLRequestHeader("Content-type","application/octet-stream");
uploadrequest.requestHeaders.push(header);
uploadrequest.method = URLRequestMethod.PUT;
uploadrequest.data = byte;
urlloader1.dataFormat = URLLoaderDataFormat.BINARY;
urlloader1.addEventListener(Event.COMPLETE,uploaded);
urlloader1.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS,displayerror);
urlloader1.load(uploadrequest);
}
protected function uploaded(event:Event):void
{
PopUpManager.removePopUp(Alert);
errormsg = "Done!";
var str:String = urlloader1.data;
PopUpManager.addPopUp(Alert,this,true);
PopUpManager.centerPopUp(Alert);
}
protected function displayerror(event:Event):void
{
errormsg = httpresponsemsg;
PopUpManager.addPopUp(Alert,this,true);
PopUpManager.centerPopUp(Alert);
}

QrCode Open Source Library for WinRT

I need to generate the Qr Code for my Windows 8 Store App.Is there any Open Source Qr Code Library which is based on Win Rt.
I have made use of zxing library which is available on codeplex.
The method I wrote is as follows:
I'm making use of the DecodeQRcode with storage file from the camera's CaptureFileAsync method which returns the storage file of the qrImgage.
public async void DecodeQRCode(StorageFile file)
{
// load a jpeg, be sure to have the Pictures Library capability in your manifest
var data = await FileIO.ReadBufferAsync(file);
// create a stream from the file
var ms = new InMemoryRandomAccessStream();
var dw = new Windows.Storage.Streams.DataWriter(ms);
dw.WriteBuffer(data);
await dw.StoreAsync();
ms.Seek(0);
// find out how big the image is, don't need this if you already know
var bm = new BitmapImage();
await bm.SetSourceAsync(ms);
// create a writable bitmap of the right size
var wb = new WriteableBitmap(bm.PixelWidth, bm.PixelHeight);
ms.Seek(0);
// load the writable bitpamp from the stream
await wb.SetSourceAsync(ms);
var lsource = new BitmapLuminanceSource(wb);
var binarizer = new HybridBinarizer(lsource);
var bbmp = new BinaryBitmap(binarizer);
var c = new QRCodeReader();
Result res= c.decode(bbmp);
}
While taking the image of the QR code you must make sure that you crop the image properly or else you won't get the expected result.
I have not used this, but ZXing.Net is....
A library which supports decoding and generating of barcodes (like QR
Code, PDF 417, EAN, UPC, Aztec, Data Matrix, Codabar) within images.
and has assembles available for WindowsRT (as well as phone)
You can use the ZXing.NET: https://zxingnet.codeplex.com/
Code for load image to get QR Code result:
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".png");
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".bmp");
StorageFile file = await openPicker.PickSingleFileAsync();
if (null != file)
{
try
{
BitmapImage bitmap = new BitmapImage();
using (IRandomAccessStream fileStream1 = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
bitmap.SetSource(fileStream1);
}
using (IRandomAccessStream fileStream2 = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
{
WriteableBitmap writeableBitmap = new WriteableBitmap(bitmap.PixelWidth, bitmap.PixelHeight);
writeableBitmap.SetSource(fileStream2); IBarcodeReader reader = new BarcodeReader();
var result = reader.Decode(writeableBitmap);
txt1.Text = result.ToString();
}
}
catch (Exception exception)
{
//
}
}
Code for get QR from camera (use the MSDN demo: http://code.msdn.microsoft.com/windowsapps/CameraCaptureUI-Sample-845a53ac and customized):
private async void CapturePhoto_Click(object sender, RoutedEventArgs e)
{
try
{
rootPage.NotifyUser("", NotifyType.StatusMessage);
// Using Windows.Media.Capture.CameraCaptureUI API to capture a photo
CameraCaptureUI dialog = new CameraCaptureUI();
Size aspectRatio = new Size(1, 1);
dialog.PhotoSettings.CroppedAspectRatio = aspectRatio;
StorageFile file = await dialog.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
BitmapImage bitmapImage = new BitmapImage();
using (IRandomAccessStream fileStream1 = await file.OpenAsync(FileAccessMode.Read))
{
bitmapImage.SetSource(fileStream1);
}
CapturedPhoto.Source = bitmapImage;
ResetButton.Visibility = Visibility.Visible;
ZXing.BarcodeReader br = new ZXing.BarcodeReader();
WriteableBitmap wrb = new WriteableBitmap(bitmapImage.PixelWidth, bitmapImage.PixelHeight);
BitmapImage img = new BitmapImage();
img.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
using (IRandomAccessStream fileStream2 = await file.OpenAsync(FileAccessMode.Read))
{
wrb.SetSource(fileStream2);
}
var res = br.Decode(wrb);
rootPage.NotifyUser(res.ToString(), NotifyType.ErrorMessage);
}
else
{
rootPage.NotifyUser("No photo captured.", NotifyType.StatusMessage);
}
}
catch (Exception ex)
{
rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage);
}
}