Getting stream from file absolute path - windows-phone-7

This may sound very simple but I've lost a lot of time looking for answer
In my Windows phone 8 app I use the PhotoChooserTask to let the user choose the photo, and i get the path of the photo by using
string FileName = e.OriginalFileName;
where e is the PhotoResult argument of the Task. , let's say: FileName=
"C:\Data\SharedData\Comms\Unistore\data\18\k\2000000a00000018700b.dat" (selected from the cloud) or
"D:\Pictures\Camera Roll\WP_20140110_10_40_42_1_Smart.jpg" (from camera roll)
I want to save that string path and open it up and show the image again when the users reopen the app. But I cannot find a method to convert those string into Image data (BitmapImage or Stream)
Any idea?

private void PhotoChooserTaskCompleted(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
var image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
SaveImageAsync(image);
}
}
public async void SaveImageAsync(BitmapImage image)
{
await Task.Run(SaveImage(image));
}
public async Task SaveImage(BitmapImage image)
{
IStorageFolder folder = await ApplicationData.Current.LocalFolder
.CreateFolderAsync("Images", CreationCollisionOption.OpenIfExists);
IStorageFile file = await folder.CreateFileAsync(
imageFileName, CreationCollisionOption.ReplaceExisting);
using (Stream stream = await file.OpenStreamForWriteAsync())
{
var wrBitmap = new WriteableBitmap(image);
wrBitmap.SaveJpeg(stream, image.PixelWidth, image.PixelHeight, 100, 100);
}
}

At Windows Phone 8.1 you can try "StorageFolder.GetFolderFromPathAsync" static method (if this API is available at your app flavor) and then get a stream for a necessary file from that folder.

Related

UWP FileOpenPicker locks\freezes app in debug

If the debugger is attached, calling this function causes the app to hang. If I run without a debugger, there is no hang, and file pickers work perfectly.
private async void OnClick(object sender, RoutedEventArgs e)
{
FileOpenPicker openPicker = new FileOpenPicker();
}
I'm certain this is something super simple, but I just don't know.
Edit:
Here's how I'm using it. Keep in mind, that the simpler function creates the hang issue without all my extra code after it. I've stuffed up the image saving, but that's a separate issue I want to debug when I solve what this post is about.
.
public async Task ImportHeader()
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
openPicker.FileTypeFilter.Add(".jpg");
openPicker.FileTypeFilter.Add(".png");
// For multiple image selection
var files = await openPicker.PickMultipleFilesAsync();
foreach (StorageFile singleImage in files)
{
IRandomAccessStream stream = await singleImage.OpenAsync(Windows.Storage.FileAccessMode.Read);
var image = new BitmapImage();
image.SetSource(stream);
HeaderImage.Source = image;
//We also save this to disk for later
Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile file = await storageFolder.CreateFileAsync("header.jpg", Windows.Storage.CreationCollisionOption.ReplaceExisting);
stream.Seek(0);
using (StreamWriter bw = new StreamWriter(file.OpenStreamForWriteAsync().Result))
{
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
var renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(HeaderImage, (int)HeaderImage.Width, (int)HeaderImage.Height);
var pixels = await renderTargetBitmap.GetPixelsAsync();
byte[] bytes = pixels.ToArray();
bw.Write(stream);
}
}
}
This has happened to me as well on some of the recent Windows 10 Insider Preview builds, while the process works flawlessly on stable builds of Windows 10. I think you can assume the cause is there instead of your code.

Taking a screenshot in Xamarin.Forms

I've looked at and tested extensively as this post. Below is the code for a screenshot button on PCL.
async void OnScreenshotButtonClicked(object sender, EventArgs args) {
var imageSender = (Image)sender;
var ScreenShot = DependencyService.Get<IScreenshotManager>().CaptureAsync();
await DisplayAlert("Image Saved", "The image has been saved to your device's picture album.", "OK");
}
So my question is how to turn byte[] into an image and save it to a device... For the life of me, I cannot figure out a way to save the image to the device. Any help would be greatly appreciated!!! Thanks!
Like Jason mentioned in the comments you can extend your code in the platform project by adding a File.WriteAllBytes(); line and save your file from right there.
Or you can decouple it and create another DependencyService. For instance create the IScreenshotService like: DependencyService.Get<IScreenshotService>().SaveScreenshot("MyScreenshot123", ScreenShot);
And create implementations like this:
PCL
public interface IScreenshotService
{
SaveScreenshot(string filename, byte[] imageBytes);`
}
iOS
[assembly: Xamarin.Forms.Dependency(typeof(ScreenshotService_iOS))]
 
namespace YourApp.iOS
{
    public class ScreenshotService_iOS: IScreenshotService
{
        public void SaveScreenshot(string filename, byte[] imageBytes)
        {
            var screenshot = new UIImage(NSData.FromArray(imageBytes));
            screenshot.SaveToPhotosAlbum((image, error) =>
            {
// Catch any error here
                if(error != null)
                    Console.WriteLine(error.ToString());
// If you want you can access the image here from the image parameter
            });
        }
    }
}
Android
[assembly: Xamarin.Forms.Dependency(typeof(Picture_Droid))]
 
namespace YourApp.Droid
{
    public class ScreenshotService_Android : IScreenshotService
{
        public void SaveScreenshot(string filename, byte[] imageBytes)
        {
            var dir = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDcim);
            
var pictures = dir.AbsolutePath;
            
// You might want to add a unique id like GUID or timestamp to the filename, else you could be overwriting an older image
            string filePath = System.IO.Path.Combine(pictures, filename);
            try
            {
// Write the image
                File.WriteAllBytes(filePath, imageData);
// With this we add the image to the image library on the device
                var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
                mediaScanIntent.SetData(Uri.FromFile(new File(filePath)));
                Xamarin.Forms.Forms.Context.SendBroadcast(mediaScanIntent);
            }
            catch(Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
    }
}
Don't forget to add the appropriate permissions on the Android app (probably WRITE_EXTERNAL_STORAGE is enough)
Lastly you could look at third-party libraries like Splat for example.

How can i open an image in it's full size in UWP

I am working on a chat app:
If the user taps on an image, it will show in full size. The following method is called:
Handle_Tapped():
void Handle_Tapped(object sender, System.EventArgs e)
{
try
{
Image image = sender as Image;
string filePath = String.Empty;
filePath = image.Source as FileImageSource;
Eva3Toolkit.CommonUtils.openImage(filePath);
}
catch (Exception ex)
{
throw ex;
}
}
Which calls (depending on the OS):
openImage() in Android:
public void openImage(string filePath)
{
Intent sendIntent = new Intent(Intent.ActionView);
sendIntent.SetDataAndType(Android.Net.Uri.Parse("file:" + filePath), "image/*");
Forms.Context.StartActivity(Intent.CreateChooser(sendIntent, "Bild öffnen..."));
}
openImage() in iOS:
public void openImage(string filePath)
{
var firstController = ((UIApplicationDelegate)(UIApplication.SharedApplication.Delegate)).Window.RootViewController.ChildViewControllers[0].ChildViewControllers[1].ChildViewControllers[0];
var navcontroller = firstController as UINavigationController;
var docIC = UIDocumentInteractionController.FromUrl(new NSUrl(filePath, true));
docIC.Delegate = new DocInteractionC(navcontroller);
docIC.PresentPreview(true);
}
Now I want to create a method openImage() in UWP, but I don't know know. I know that I will most likely have to work with the image as a StorageFile instead of the path because only a StorageFile grants me permission to open the image.
Is there a way to open the image in full size in UWP? I highly prefer to not create a new view for this.
A Launcher can open a file with the program that is assigned to the file:
public async void openImageAsync(string filePath)
{
StorageFile storageFile = await StorageFile.GetFileFromPathAsync(filePath);
await Launcher.LaunchFileAsync(storageFile);
}
For my situation it's working that I use filePath because the files are in a local folder.
The output looks like this:

Screenshot in windows phone 7

Can anyone please tell me how to take screenshot and save it to the folder programmatically in windows phone 7.I don't want to save images in the MediaLibrary(),but i want to save it into the folder which is in the root directory of the application
This code will help you to take screenshot against an AppBar button click action. However you have to modify the code to save screenshot into root folder of the Application. The following links will help you.
Save into local storage
Data for Windows Phone
private void ApplicationBarScreenshotButton_Click(object sender, EventArgs e)
{
var fileName = String.Format("MyImage_{0:}.jpg", DateTime.Now.Ticks);
WriteableBitmap bmpCurrentScreenImage = new WriteableBitmap((int)this.ActualWidth, (int)this.ActualHeight);
bmpCurrentScreenImage.Render(LayoutRoot, new MatrixTransform());
bmpCurrentScreenImage.Invalidate();
SaveToMediaLibrary(bmpCurrentScreenImage, fileName, 100);
MessageBox.Show("Captured image " + fileName + " Saved Sucessfully", "WP Capture Screen", MessageBoxButton.OK);
currentFileName = fileName;
}
public void SaveToMediaLibrary(WriteableBitmap bitmap, string name, int quality)
{
using (var stream = new MemoryStream())
{
// Save the picture to the Windows Phone media library.
bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, quality);
stream.Seek(0, SeekOrigin.Begin);
// Use Above link to store file into Root folder.
//new MediaLibrary().SavePicture(name, stream);
}
}

Base64ToImage in Windows 8 Store App

In my Windows 8 app I get an image as base64 string. Now I am looking for a method that converts the string so that I can include it in my XAML image, something like this:
public static Image Base64ToImage(string s)
{
// How To?
}
I have seen many solutions but all of them use classes/methods that are not available in Windows 8 store apps. Thanks for your hints.
The method could look like this:
private async Task<BitmapImage> Base64ToImage(string base64)
{
var bitmap = new BitmapImage();
var buffer = Convert.FromBase64String(base64);
using (var stream = new InMemoryRandomAccessStream())
{
await stream.WriteAsync(buffer.AsBuffer());
stream.Seek(0);
bitmap.SetSource(stream);
}
return bitmap;
}

Resources