how save image to folder from Image control Win 8 apps - c#

I have a Image control
<Image Name="img" HorizontalAlignment="Left" Height="400" Margin="499,155,0,0" VerticalAlignment="Top" Width="400"/>
And I capture photo from Camera
private async void TakePhoto_Click(object sender, RoutedEventArgs e)
{
CameraCaptureUI camera = new CameraCaptureUI();
camera.PhotoSettings.CroppedAspectRatio = new Size(4, 3);
var photo = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (photo != null)
{
BitmapImage image = new BitmapImage();
image.SetSource(await photo.OpenAsync(FileAccessMode.Read));
img.Source = image;
}
}
And now I want to save this image from img control to folder, but I don't know how decode image from img control to StorageFile
private async void SaveFile_Click(object sender, RoutedEventArgs e)
{
FileSavePicker savePicker = new FileSavePicker();
savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
savePicker.FileTypeChoices.Add("jpeg image", new List<string>() { ".jpeg" });
savePicker.SuggestedFileName = "New picture";
StorageFile ff = await savePicker.PickSaveFileAsync();
if (ff != null)
{
await photo.MoveAndReplaceAsync(ff);
}
}
this is a save method, which i want to save image from Image control

The
var photo = await camera.CaptureFileAsync(CameraCaptureUIMode.Photo); returns a StorageFile. All you have to do is save it to the location you want.
You can accomplish this in may ways.
Example:
StorageFolder localFolder = ApplicationData.Current.LocalFolder; // the app's local storage folder
await photo.MoveAsync(localFolder); //move the file to a new location
2.
//Create a new copy in a new location
await photo.CopyAsync(localFolder);
Note that var photo == StorageFile photo. This means that the after the photo was captured, a copy of it was already saved to a temporary location(The App's TempState directory) on the local storage.

Related

UWP drag and drop from WebView onto Canvas

I tried this code. I drag Image from WebView to Canvas. But nothing to be show. Maybe dropped data is URL or html data. BUt I don't know how to convert html data to Bitmap data.
private async void drop(object sender, DragEventArgs e)
{
if (e.DataView.Contains(StandardDataFormats.StorageItems))
{
var items = await e.DataView.GetStorageItemsAsync();
if (items.Count > 0)
{
Point drop = e.GetPosition(Board);
var storageFile = items[0] as StorageFile;
var bitmapImage = new BitmapImage();
bitmapImage.SetSource(await storageFile.OpenAsync(FileAccessMode.Read));
Image img = new Image();
img.Source = bitmapImage;
img.Width = 200;
img.Height = 150;
Canvas.SetLeft(img, drop.X);
Canvas.SetTop(img, drop.Y);
Board.Children.Add(img);
}
}
}
XAML is below.
<WebView x:Name="WebView" Source="https://google.com" ScriptNotify="Notify" NavigationCompleted="Completed" ></WebView>
<Canvas AllowDrop="True" DragOver="dragOver" Drop="drop"></Canvas>

WPF : how to save stroke collection to bitmap?

I use InkCanvas to implement signature function.
after signed, I can use RenderTargetBitmap class to save the signature-drawing into bitmap.
but RenderTargetBitmap always save InkCanvas itself, means can not save ONLY the signature content.
my question is, how to save StrokeCollection into bitmap?
I think you should use Win2D (Win2D.uwp NuGet package); it is pretty easy.
Here is the code:
async void SaveAsBitmap(object sender, RoutedEventArgs e)
{
//copy from origianl canvas and paste on the new canvas for saving
var strokes = inkCanvas.InkPresenter.StrokeContainer.GetStrokes();
//check if canvas is not empty
if (strokes.Count == 0) return;
//select all the strokes to be copied to the clipboard
foreach (var stroke in strokes)
{
stroke.Selected = true;
}
inkCanvas.InkPresenter.StrokeContainer.CopySelectedToClipboard();
//paste the strokes to a new InkCanvas and move the strokes to the topper left corner
var newCanvas = new InkCanvas();
newCanvas.InkPresenter.StrokeContainer.PasteFromClipboard(new Point(0, 0));
//using Win2D to save ink as png
CanvasDevice device = CanvasDevice.GetSharedDevice();
CanvasRenderTarget renderTarget = new CanvasRenderTarget(device,
(int)inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Width,
(int)inkCanvas.InkPresenter.StrokeContainer.BoundingRect.Height,
96);
using (var ds = renderTarget.CreateDrawingSession())
{
//ds.Clear(Colors.White); //uncomment this line for a white background
ds.DrawInk(newCanvas.InkPresenter.StrokeContainer.GetStrokes());
}
//save file dialog
var savePicker = new Windows.Storage.Pickers.FileSavePicker()
{
SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.DocumentsLibrary
};
savePicker.FileTypeChoices.Add("Image file", new List<string>() { ".jpeg", ".png" });
savePicker.SuggestedFileName = "mysign.png";
var file = await savePicker.PickSaveFileAsync();
if (file != null)
{
using (var fileStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
await renderTarget.SaveAsync(fileStream, CanvasBitmapFileFormat.Png);
}
}
}

Work with image picked by File Picker in windows phone 8.1

I want to workk with an image picked by file picker in windows phone 8.1.I picked an image using this code
private async void gallery_Tapped(object sender, TappedRoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".jpeg");
openPicker.FileTypeFilter.Add(".png");
// Launch file open picker and caller app is suspended and may be terminated if required
openPicker.PickSingleFileAndContinue();
}
public async void ContinueFileOpenPicker(FileOpenPickerContinuationEventArgs args)
{
if (args.Files.Count > 0)
{
StorageFile file=args.Files[0];
IRandomAccessStream fileStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
BitmapImage bitmapImage = new BitmapImage();
bitmapImage.SetSource(fileStream);
MyImage.Source=bitmapImage;
}
else
{
}
}
ContinueFileOpenPicker not executing I tried this but unable to understand that.Can any here guide me step by step what should I do to make it work.Thanks
protected override void OnActivated(IActivatedEventArgs args)
{
var root = Window.Current.Content as Frame;
var mainPage = root.Content as MainPage;
if (mainPage != null && args is FileOpenPickerContinuationEventArgs)
{
mainPage.ContinueFileOpenPicker(args as FileOpenPickerContinuationEventArgs);
}
}
Put this code in app.xaml.cs it will work..

Windows 8 c# save a camera's picture on local storage

I'm new to C# and I want to create an application metro who can take picture and save themself in localstorage. I know, i need to use isolated storage but i really don't understand how to use it for image. I saw a lot of examples for string but not for picture.
If anyone know how to do it ? Actually i take a picture and i ask the user to record it where he wants. But I want an auto record after the user take the picture. This my code for the moment :
private async void Camera_Clicked(object sender, TappedRoutedEventArgs e)
{
CameraCaptureUI camera = new CameraCaptureUI();
camera.PhotoSettings.CroppedAspectRatio = new Size(16, 9);
StorageFile photo = await camera.
CaptureFileAsync(CameraCaptureUIMode.Photo);
if (photo != null)
{
BitmapImage bmp = new BitmapImage();
IRandomAccessStream stream = await photo.
OpenAsync(FileAccessMode.Read);
bmp.SetSource(stream);
ImageSource.Source = bmp;
ImageSource.Visibility = Visibility.Visible;
appSettings[photoKey] = photo.Path;
FileSavePicker savePicker = new FileSavePicker();
savePicker.FileTypeChoices.Add
("jpeg image", new List<string>() { ".jpeg" });
savePicker.SuggestedFileName = "New picture";
StorageFile ff = await savePicker.PickSaveFileAsync();
if (ff != null)
{
await photo.MoveAndReplaceAsync(ff);
}
}
}
All what you need to do is to replace File Picker logic with retrieving of StorageFile object in Local folder, for example like this:
private async void Camera_Clicked(object sender, TappedRoutedEventArgs e)
{
CameraCaptureUI camera = new CameraCaptureUI();
camera.PhotoSettings.CroppedAspectRatio = new Size(16, 9);
StorageFile photo = await camera.
CaptureFileAsync(CameraCaptureUIMode.Photo);
if (photo != null)
{
var targetFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("some_file_name.jpg");
if (targetFile != null)
{
await photo.MoveAndReplaceAsync(targetFile);
}
}
}

Setting Image source programatically in Metro app, Image doesn't appear

I have a main page and a camera page in my application. The main page has an image that does not have its source set and a button. If you click the button, it will take you to the camera page. On the camera page, I capture an image and save it in the pictures library on the tablet and then navigate back to the main page where I would like to set the source of the image to the image I just captured and saved in my pictures library. Here is my relevant code.
MainPage.xaml
<Image x:Name="imgResume" HorizontalAlignment="Left" Height="303" Margin="975,60,0,0" Grid.Row="1" VerticalAlignment="Top" Width="360" Stretch="UniformToFill" Loaded="img_OnLoaded"/>
<Button x:Name="btnCamera" Content="Camera" HorizontalAlignment="Left" Margin="1128,372,0,0" Grid.Row="1" VerticalAlignment="Top" RenderTransformOrigin="2.05800008773804,0.184000000357628" Height="59" Width="108" Click="Camera_Click" IsEnabled="False"/>
MainPage.xaml.cs
private void img_OnLoaded(object sender, RoutedEventArgs e)
{
if (txtFirstName.Text != "" && txtLastName.Text != "")
{
try
{
imgResume.Source = ImageFromRelativePath(this, Windows.Storage.KnownFolders.PicturesLibrary.Path + ((App)Application.Current).candidate.FirstName + ((App)Application.Current).candidate.FirstName + "Resume.jpg");
imgResume.UpdateLayout();
}
catch
{
imgResume.Source = ImageFromRelativePath(this, #"Assets/logo.png");
imgResume.UpdateLayout();
}
btnCamera.IsEnabled = true;
}
}
public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path)
{
var uri = new Uri(parent.BaseUri, path);
BitmapImage result = new BitmapImage();
result.UriSource = uri;
return result;
}
Camera.xaml.cs
private async void Capture_Click(object sender, RoutedEventArgs e)
{
if (mediaCaptureMgr != null)
{
string firstName = ((App)Application.Current).candidate.FirstName;
string lastName = ((App)Application.Current).candidate.LastName;
string fileName = firstName + lastName + "Resume.jpg";
Windows.Storage.IStorageFile photo = await Windows.Storage.KnownFolders.PicturesLibrary.CreateFileAsync(fileName, Windows.Storage.CreationCollisionOption.ReplaceExisting);
await mediaCaptureMgr.CapturePhotoToStorageFileAsync(Windows.Media.MediaProperties.ImageEncodingProperties.CreateJpeg(), photo);
this.Frame.Navigate(typeof(BasicPersonalInfo));
}
}
The img_OnLoaded method in the MainPage.xaml file is attempting to set the image source to the image that I save to the pictures library from the Capture_click method in the Camera.xaml.cs.
My problem is that the picture never shows up on the image on the first page! Please help!
This may also be helpful to people trying to solve the related problem of updating an Image from a local resource file.
myImage.Source = ImageFromRelativePath(this, "relative_path_to_file_make_sure_build_set_to_content");
public static BitmapImage ImageFromRelativePath(FrameworkElement parent, string path)
{
var uri = new Uri(parent.BaseUri, path);
BitmapImage result = new BitmapImage();
result.UriSource = uri;
return result;
}
Code is from here.
I think this part is the problem:
var uri = new Uri(parent.BaseUri, path);
That seems to try to load the image from the installation folder while your path is a full path, which I believe is not supported for opening files in WinRT and certainly does not work as a Uri even with a baseUri.
You should instead do something like:
var file = await Windows.Storage.KnownFolders.PicturesLibrary.GetFileAsync(((App)Application.Current).candidate.FirstName + "Resume.jpg");
var stream = await file.OpenReadAsync();
var bi = new BitmapImage();
bi.SetSource(stream);
return bi;

Categories