Save App.RootFrame Background in wp8 - c#

I am using PhotoChooserTaskto pick a picture from photo gallery and then set this picture as my app background. Everything works fine, but when I exit my application it's not saved. What I am looking is to save this background for my application.
I am using below code:
photoChooserTask = new PhotoChooserTask()
photoChooserTask.Completed += new EventHandler<PhotoResult>(photoChooserTask_Completed);
void photoChooserTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
System.IO.IsolatedStorage.IsolatedStorageSettings settings = System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings;
System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
bmp.SetSource(e.ChosenPhoto);
imgCustom.Source = bmp;
System.Windows.Media.ImageBrush backgroundBrush = new System.Windows.Media.ImageBrush() { ImageSource = bmp };
App.RootFrame.Background = backgroundBrush;
}
}
What I am looking is, If I close and run my application, This background should not change unless the user changes it.
Thanks!

How about trying out this piece of code at the end:
var frame = App.Current.RootVisual as PhoneApplicationFrame;
frame.Background = backgroundBrush;
Reference: Windows Phone app background image

Related

Display Video Frame of WebCam in C# Window Form

I am currently using my Webcam to display video frame by creating another window. However, I had reserved a box for video displaying in my window form application and try not to create another window for video frame. How could i do it?
Attach my code for creating new video:
VideoCapture capture;
Mat frame;
capture = new VideoCapture();
frame = new Mat();
capture.Open(0);
string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test1.jpg";
//// Read the video stream
Cv2.NamedWindow("Video", WindowMode.AutoSize);
while (true)
{
if (capture.Read(frame))
{
Cv2.ImShow("Video", frame);
}
}
My window form application:
private void EmoStart_Click(object sender, EventArgs e)
{
VideoCapture capture;
Mat frame;
string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test1.jpg";
capture = new VideoCapture();
frame = new Mat();
capture.Open(0);
while (true)
{
if (capture.Read(frame))
{
pictureBox1.Image = capture.Read(frame);
}
}
}
Could the picture box read the captured frame?
When i try to open up another windows, both of them are freezed.
How could i attach the Webcam frame to my application form?
Thank you!

Aspose OCR - Not Recognising Image

I'm playing around with Aspose OCR and it's reading images with white backgrounds and black text fine. However, anything with a black or different colour background it does not read.
Any idea how to get around this?
private void timer1_Tick(object sender, EventArgs e)
{
//SendKeys.Send("{PRTSC}");
Image img = Clipboard.GetImage();
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Image = img;
if (img != null)
{
var ms = new MemoryStream();
img.Save(ms, ImageFormat.Jpeg); // put here the image format
ms.Position = 0;
ocr.Image = ImageStream.FromStream(ms, ImageStreamFormat.Jpg);
if (ocr.Process()) // Start processing it
{
label1.Text = "Text: " + ocr.Text;
}
}
}
You may try the following line of code. Further to update you that development on processing of color back ground image feature is in-progress.
ocr.Config.ProcessColoredBackground = true;
I work with Aspose as Developer evangelist.

Delete or have Control of an Image while your Application is Using it C#

I’m using WinForms. In my form I have a picturebox. On form load, my program opens an image document into my picturebox from my C:/image directory. The problem is when my program opens that image I cannot go into my C:/image directory and delete this picture because my application is using it. When I go to C:/image directory and try to delete the picture I get this error.
My goal is to have control over the image document that means i have the ability to delete the specific document even if its being used by my application.
Test: I tested if you can delete an image while viewing it at the same time with "Windows Photo Viewer" installed into in my computer, and that application lets you. Windows photo viewer doesn't lock the images. When you delete an image from the directory the image goes away in windows photo viewer as well. I want to accomplish something similar.
Suggested code: I tried implementing this but, i think i'm implementing it incorrectly.
Image img;
using (var bmpTemp = new Bitmap("image_file_path"))
{
img = new Bitmap(bmpTemp);
}
Below i provided my code i wrote to load the picture into my picture box.
private void Form1_Load(object sender, EventArgs e) //When form load you do this:
{
try // Get the tif file from C:\image\ folder
{
string path = #"C:\image\";
string[] filename = Directory.GetFiles(path, "*.tif"); //gets a specific image doc.
pictureBox1.Load(filename[0]);
lblFile.Text = filename[0];
RefreshImage(); // refreshing and showing the new file
opened = true; // the files was opened.
Image img1 = Image.FromFile(lblFile.Text);
pictureBox1.Image = img1;
pictureBox1.Width = img1.Width;
pictureBox1.Height = img1.Height;
picWidth = pictureBox1.Width;
picHeight = pictureBox1.Height;
getRatio();
}
catch (Exception ex)
{
MessageBox.Show("No files or " + ex.Message);
}
}
Make a copy of the image file bits before creating the image:
private void Form1_Load(object sender, EventArgs e) //When form load you do this:
{
try // Get the tif file from C:\image\ folder
{
string path = #"C:\image\";
string[] filename = Directory.GetFiles(path, "*.tif"); //gets a specific image doc.
FileInfo fi = new FileInfo(filename[0]);
byte [] buff = new byte[fi.Length];
using ( FileStream fs = File.OpenRead(fileToDisplay) )
{
fs.Read(buff, 0, (int)fi.Length);
}
MemoryStream ms = new MemoryStream(buff);
Bitmap img1 = new Bitmap(ms);
opened = true; // the files was opened.
pictureBox1.Image = img1;
pictureBox1.Width = img1.Width;
pictureBox1.Height = img1.Height;
picWidth = pictureBox1.Width;
picHeight = pictureBox1.Height;
getRatio();
}
catch (Exception ex)
{
MessageBox.Show("No files or " + ex.Message);
}
}

How to access the camera from my Windows Phone 8 app (XAML and C#) and save the taken picture in a determined folder?

I want the Windows Phone 8 app that I am building at this moment to access the camera for taking a photo when a concrete button on the screen is pressed and then save the image that has been taken into a determined folfer (a folder created into the Windows Phone project by me, not the Windows Phone default image gallery).
Could you help me accesing the camera, taking the picture and saving it into the folder created by me, please? I am using XAML and C#.
Thank you so much!!!
I would recommend PhotoCamera class if capture is to be processed on a button in the app
PhotoCamera myCamera = new Microsoft.Devices.PhotoCamera(CameraType.Primary);
//viewfinderBrush is a videobrush object declared in xaml
viewfinderBrush.SetSource(myCamera);
myCamera.Initialized += myCamera_Initialized;
myCamera.CaptureCompleted += new EventHandler<CameraOperationCompletedEventArgs>(camera_CaptureCompleted);
myCamera.CaptureImageAvailable += new EventHandler<Microsoft.Devices.ContentReadyEventArgs>(camera_CaptureImageAvailable);
//Events
void myCamera_Initialized(object sender, CameraOperationCompletedEventArgs e)
{
try
{
if (e.Succeeded)
{
}
}
catch
{
MessageBox.Show("Problem occured in camera initialization.");
}
}
void camera_CaptureCompleted(object sender, CameraOperationCompletedEventArgs e)
{
try
{
}
catch
{
MessageBox.Show("Captured image is not available, please try again.");
}
}
void camera_CaptureImageAvailable(object sender, Microsoft.Devices.ContentReadyEventArgs e)
{
try
{
}
catch (Exception ex)
{
MessageBox.Show("Captured image is not available, please try again. " + ex.Message);
}
}
And there is one more alternative called CameraCaptureTask
CameraCaptureTask cameraCaptureTask;
cameraCaptureTask = new CameraCaptureTask();
cameraCaptureTask.Completed += new EventHandler<PhotoResult>(cameraCaptureTask_Completed);
cameraCaptureTask.Show();
void cameraCaptureTask_Completed(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
MessageBox.Show(e.ChosenPhoto.Length.ToString());
//Code to display the photo on the page in an image control named myImage.
//System.Windows.Media.Imaging.BitmapImage bmp = new System.Windows.Media.Imaging.BitmapImage();
//bmp.SetSource(e.ChosenPhoto);
//myImage.Source = bmp;
}
}
Check this for PhotoCamera class
And this for CameraCaptureTask
There's a simple code demonstration here showing your to put the camera API to use for Windows Phone8 apps.
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if ((PhotoCamera.IsCameraTypeSupported(CameraType.Primary) == true) ||
(PhotoCamera.IsCameraTypeSupported(CameraType.FrontFacing) == true)) {
// Initialize the default camera.
_photoCamera = new Microsoft.Devices.PhotoCamera();
//Event is fired when the PhotoCamera object has been initialized
_photoCamera.Initialized += new EventHandler<Microsoft.Devices.CameraOperationCompletedEventArgs>(OnPhotoCameraInitialized);
//Set the VideoBrush source to the camera
viewfinderBrush.SetSource(_photoCamera);
}
else {
// The camera is not supported on the device.
this.Dispatcher.BeginInvoke(delegate() {
// Write message.
txtDebug.Text = "A Camera is not available on this device.";
});
}
}
private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e) {
int width = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
int height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);
}
Dont forget to add this line in WMAppManifent.xml file.
<Capability Name="ID_CAP_ISV_CAMERA"/>
you can read here ,
Using Cameras in Your Windows Phone Application

Asynchronously Loading a BitmapImage in C# using WPF

What's the best way to asynchronously load an BitmapImage in C# using WPF?
I was just looking into this and had to throw in my two cents, though a few years after the original post (just in case any one else comes looking for this same thing I was looking into).
I have an Image control that needs to have it's image loaded in the background using a Stream, and then displayed.
The problem that I kept running into is that the BitmapSource, it's Stream source and the Image control all had to be on the same thread.
In this case, using a Binding and setting it's IsAsynch = true will throw a cross thread exception.
A BackgroundWorker is great for WinForms, and you can use this in WPF, but I prefer to avoid using the WinForm assemblies in WPF (bloating of a project is not recommended, and it's a good rule of thumb too). This should throw an invalid cross reference exception in this case too, but I didn't test it.
Turns out that one line of code will make any of these work:
//Create the image control
Image img = new Image {HorizontalAlignment = System.Windows.HorizontalAlignment.Stretch, VerticalAlignment = System.Windows.VerticalAlignment.Stretch};
//Create a seperate thread to load the image
ThreadStart thread = delegate
{
//Load the image in a seperate thread
BitmapImage bmpImage = new BitmapImage();
MemoryStream ms = new MemoryStream();
//A custom class that reads the bytes of off the HD and shoves them into the MemoryStream. You could just replace the MemoryStream with something like this: FileStream fs = File.Open(#"C:\ImageFileName.jpg", FileMode.Open);
MediaCoder.MediaDecoder.DecodeMediaWithStream(ImageItem, true, ms);
bmpImage.BeginInit();
bmpImage.StreamSource = ms;
bmpImage.EndInit();
//**THIS LINE locks the BitmapImage so that it can be transported across threads!!
bmpImage.Freeze();
//Call the UI thread using the Dispatcher to update the Image control
Dispatcher.BeginInvoke(new ThreadStart(delegate
{
img.Source = bmpImage;
img.Unloaded += delegate
{
ms.Close();
ms.Dispose();
};
grdImageContainer.Children.Add(img);
}));
};
//Start previously mentioned thread...
new Thread(thread).Start();
Assuming you're using data binding, setting Binding.IsAsync property to True seems to be a standard way to achieve this.
If you're loading the bitmap in the code-behind file using background thread + Dispatcher object is a common way to update UI asynchronous
This will allow you to create the BitmapImage on the UI thread by using the HttpClient to do the async downloading:
private async Task<BitmapImage> LoadImage(string url)
{
HttpClient client = new HttpClient();
try
{
BitmapImage img = new BitmapImage();
img.CacheOption = BitmapCacheOption.OnLoad;
img.BeginInit();
img.StreamSource = await client.GetStreamAsync(url);
img.EndInit();
return img;
}
catch (HttpRequestException)
{
// the download failed, log error
return null;
}
}
To elaborate onto aku's answer, here is a small example as to where to set the IsAsync:
ItemsSource="{Binding IsAsync=True,Source={StaticResource ACollection},Path=AnObjectInCollection}"
That's what you would do in XAML.
BitmapCacheOption.OnLoad
var bmp = await System.Threading.Tasks.Task.Run(() =>
{
BitmapImage img = new BitmapImage();
img.BeginInit();
img.CacheOption = BitmapCacheOption.OnLoad;
img.UriSource = new Uri(path);
img.EndInit();
ImageBrush brush = new ImageBrush(img);
}
Use or extend System.ComponentModel.BackgroundWorker:
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
Personally, I find this to be the easiest way to perform asynchronous operations in client apps. (I've used this in WinForms, but not WPF. I'm assuming this will work in WPF as well.)
I usually extend Backgroundworker, but you dont' have to.
public class ResizeFolderBackgroundWorker : BackgroundWorker
{
public ResizeFolderBackgroundWorker(string sourceFolder, int resizeTo)
{
this.sourceFolder = sourceFolder;
this.destinationFolder = destinationFolder;
this.resizeTo = resizeTo;
this.WorkerReportsProgress = true;
this.DoWork += new DoWorkEventHandler(ResizeFolderBackgroundWorker_DoWork);
}
void ResizeFolderBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
DirectoryInfo dirInfo = new DirectoryInfo(sourceFolder);
FileInfo[] files = dirInfo.GetFiles("*.jpg");
foreach (FileInfo fileInfo in files)
{
/* iterate over each file and resizing it */
}
}
}
This is how you would use it in your form:
//handle a button click to start lengthy operation
private void resizeImageButtonClick(object sender, EventArgs e)
{
string sourceFolder = getSourceFolderSomehow();
resizer = new ResizeFolderBackgroundWorker(sourceFolder,290);
resizer.ProgressChanged += new progressChangedEventHandler(genericProgressChanged);
resizer.RunWorkerCompleted += new RunWorkerCompletedEventHandler(genericRunWorkerCompleted);
progressBar1.Value = 0;
progressBar1.Visible = true;
resizer.RunWorkerAsync();
}
void genericRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
progressBar1.Visible = false;
//signal to user that operation has completed
}
void genericProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
//I just update a progress bar
}

Categories

Resources