/// <summary> /// Handles result of capture to save image information /// </summary> /// <param name="sender"></param> /// <param name="e">stores information about current captured image</param> private void cameraTask_Completed(object sender, PhotoResult e) { if (e.Error != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR)); return; } switch (e.TaskResult) { case TaskResult.OK: try { string fileName = System.IO.Path.GetFileName(e.OriginalFileName); // Save image in media library MediaLibrary library = new MediaLibrary(); Picture image = library.SavePicture(fileName, e.ChosenPhoto); // Save image in isolated storage // we should return stream position back after saving stream to media library e.ChosenPhoto.Seek(0, SeekOrigin.Begin); byte[] imageBytes = new byte[e.ChosenPhoto.Length]; e.ChosenPhoto.Read(imageBytes, 0, imageBytes.Length); string pathLocalStorage = this.SaveImageToLocalStorage(fileName, isoFolder, imageBytes); // Get image data MediaFile data = new MediaFile(pathLocalStorage, image); this.files.Add(data); if (files.Count < this.captureImageOptions.Limit) { cameraTask.Show(); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files, "navigator.device.capture._castMediaFile")); files.Clear(); } } catch (Exception ex) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error capturing image.")); } break; case TaskResult.Cancel: if (files.Count > 0) { // User canceled operation, but some images were made DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files, "navigator.device.capture._castMediaFile")); files.Clear(); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Canceled.")); } break; default: if (files.Count > 0) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files, "navigator.device.capture._castMediaFile")); files.Clear(); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Did not complete!")); } break; } }
/// <summary> /// Handles result of capture to save image information /// </summary> /// <param name="sender"></param> /// <param name="e">stores information about current captured image</param> private void cameraTask_Completed(object sender, PhotoResult e) { if (e.Error != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR)); return; } switch (e.TaskResult) { case TaskResult.OK: try { string fileName = System.IO.Path.GetFileName(e.OriginalFileName); // Save image in media library MediaLibrary library = new MediaLibrary(); Picture image = library.SavePicture(fileName, e.ChosenPhoto); int orient = ImageExifHelper.getImageOrientationFromStream(e.ChosenPhoto); int newAngle = 0; switch (orient) { case ImageExifOrientation.LandscapeLeft: newAngle = 90; break; case ImageExifOrientation.PortraitUpsideDown: newAngle = 180; break; case ImageExifOrientation.LandscapeRight: newAngle = 270; break; case ImageExifOrientation.Portrait: default: break; // 0 default already set } Stream rotImageStream = ImageExifHelper.RotateStream(e.ChosenPhoto, newAngle); // Save image in isolated storage // we should return stream position back after saving stream to media library rotImageStream.Seek(0, SeekOrigin.Begin); byte[] imageBytes = new byte[rotImageStream.Length]; rotImageStream.Read(imageBytes, 0, imageBytes.Length); rotImageStream.Dispose(); string pathLocalStorage = this.SaveImageToLocalStorage(fileName, isoFolder, imageBytes); imageBytes = null; // Get image data MediaFile data = new MediaFile(pathLocalStorage, image); this.files.Add(data); if (files.Count < this.captureImageOptions.Limit) { cameraTask.Show(); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files)); files.Clear(); } } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error capturing image.")); } break; case TaskResult.Cancel: if (files.Count > 0) { // User canceled operation, but some images were made DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files)); files.Clear(); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Canceled.")); } break; default: if (files.Count > 0) { DispatchCommandResult(new PluginResult(PluginResult.Status.OK, files)); files.Clear(); } else { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Did not complete!")); } break; } }
private void saveImage_Click(object sender, EventArgs e) { if (!NetWorkAvailable()) { MessageBox.Show("Sorry, There is some problem with internet connectivity"); return; } if (!string.IsNullOrEmpty(_imagePath)) { string imagePath = _imagePath; if (imagePath.ToLower().Contains("cdn.mobstac.com")) { imagePath = imagePath.Replace(".jpg&w=400", ".jpg"); } string fileName = Path.GetFileName(imagePath); var webClient = new WebClient(); webClient.OpenReadCompleted += (object websender, OpenReadCompletedEventArgs ex) => { try { if (ex.Cancelled == true) { MessageBox.Show("Some problem in downloaing the image"); return; } if (ex.Error != null) { MessageBox.Show(string.Format("Some problem in downloaing the image: {0}", ex.Error.ToString())); return; } else { var streamResourceInfo = new StreamResourceInfo(ex.Result, null); var userStoreForApplication = IsolatedStorageFile.GetUserStoreForApplication(); if (userStoreForApplication.FileExists(fileName)) { userStoreForApplication.DeleteFile(fileName); } var isolatedStorageFileStream = userStoreForApplication.CreateFile(fileName); var bitmapImage = new BitmapImage { CreateOptions = BitmapCreateOptions.None }; bitmapImage.SetSource(streamResourceInfo.Stream); var writeableBitmap = new WriteableBitmap(bitmapImage); writeableBitmap.SaveJpeg(isolatedStorageFileStream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 85); isolatedStorageFileStream.Close(); isolatedStorageFileStream = userStoreForApplication.OpenFile(fileName, FileMode.Open, FileAccess.Read); // Save the image to the camera roll or saved pictures album. var mediaLibrary = new MediaLibrary(); // Save the image to the saved pictures album. Picture picture = mediaLibrary.SavePicture(fileName, isolatedStorageFileStream); if (picture.Name.Contains(fileName)) { DispatcherHelper.UIDispatcher.BeginInvoke(() => { MessageBox.Show(string.Format("successfully saved the image in picture hub")); }); } else { DispatcherHelper.UIDispatcher.BeginInvoke(() => { MessageBox.Show(string.Format("Sorry, Failed to save the image")); }); } isolatedStorageFileStream.Close(); } } catch (Exception) { DispatcherHelper.UIDispatcher.BeginInvoke(() => { MessageBox.Show(string.Format("Sorry, Failed to save the image")); }); } }; webClient.OpenReadAsync(new Uri(imagePath, UriKind.RelativeOrAbsolute)); } else { MessageBox.Show("Sorry, failed to save the image"); } }
/// <summary> /// Method which actually saves the image to the cameraroll. /// This code was provided to me by Nokia /// </summary> /// <param name="imgStream">Stream of the image that we want to save</param> private void SaveImage(Stream imgStream, int tileIndex, WriteableBitmap wbmp, string saveFileName, bool saveToCameraRoll) { MediaLibrary library = new MediaLibrary(); string imageName = saveFileName; var myStore = IsolatedStorageFile.GetUserStoreForApplication(); //tileIndex will be < = if we want to save to cameraroll/saved pictures if (tileIndex <= 0) { Picture p = saveToCameraRoll ? library.SavePictureToCameraRoll(imageName, imgStream) : library.SavePicture(imageName, imgStream); MessageBox.Show("Image Saved to 'Saved Pictures'"); } //remove the file from isolated storage string tempFile = imageName.Replace(".jpg", "_jpg.jpg"); if (myStore.FileExists(tempFile)) { myStore.DeleteFile(tempFile); } //otherewise save to live tiles if (tileIndex > 0 && tileIndex < 10) { string fileName = "/Shared/ShellContent/tile" + tileIndex + ".jpg"; using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream(fileName, FileMode.OpenOrCreate, myStore)) { wbmp.SaveJpeg(isoStream, wbmp.PixelWidth, wbmp.PixelHeight, 0, 100); } } myStore.Dispose(); }
private void ProcessTransfer(BackgroundTransferRequest transfer) { switch (transfer.TransferStatus) { case TransferStatus.Completed: if (transfer.StatusCode == 200 || transfer.StatusCode == 206) { // Remove the transfer request in order to make room in the // queue for more transfers. Transfers are not automatically // removed by the system. ReceivedChatBubble chatBubble; requestIdChatBubbleMap.TryGetValue(transfer.RequestId, out chatBubble); if (chatBubble != null) { chatBubble.setAttachmentState(Attachment.AttachmentState.COMPLETED); } RemoveTransferRequest(transfer.RequestId); //RemoveTransferRequest(transfer.RequestId); // In this example, the downloaded file is moved into the root // Isolated Storage directory if (transfer.UploadLocation == null) { using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication()) { string destinationPath = HikeConstants.FILES_BYTE_LOCATION + transfer.Tag; string destinationDirectory = destinationPath.Substring(0, destinationPath.LastIndexOf("/")); if (isoStore.FileExists(destinationPath)) { isoStore.DeleteFile(destinationPath); } if (!isoStore.DirectoryExists(destinationDirectory)) { isoStore.CreateDirectory(destinationDirectory); } isoStore.MoveFile(transfer.DownloadLocation.OriginalString, destinationPath); isoStore.DeleteFile(transfer.DownloadLocation.OriginalString); if (chatBubble != null && chatBubble.FileAttachment.ContentType.Contains(HikeConstants.IMAGE)) { IsolatedStorageFileStream myFileStream = isoStore.OpenFile(destinationPath, FileMode.Open, FileAccess.Read); MediaLibrary library = new MediaLibrary(); myFileStream.Seek(0, 0); library.SavePicture(chatBubble.FileAttachment.FileName, myFileStream); } var currentPage = ((App)Application.Current).RootFrame.Content as NewChatThread; if (currentPage != null) { currentPage.displayAttachment(chatBubble, true); } } } else { } } else { try { RemoveTransferRequest(transfer.RequestId); // This is where you can handle whatever error is indicated by the // StatusCode and then remove the transfer from the queue. if (transfer.TransferError != null) { // Handle TransferError if one exists. } } catch (InvalidOperationException) { } } break; case TransferStatus.WaitingForExternalPower: WaitingForExternalPower = true; break; case TransferStatus.WaitingForExternalPowerDueToBatterySaverMode: WaitingForExternalPowerDueToBatterySaverMode = true; break; case TransferStatus.WaitingForNonVoiceBlockingNetwork: WaitingForNonVoiceBlockingNetwork = true; break; case TransferStatus.WaitingForWiFi: WaitingForWiFi = true; break; } }
/// <summary> /// Saves the WriteableBitmap encoded as JPEG to the Media library. /// </summary> /// <param name="bitmap">The WriteableBitmap to save.</param> /// <param name="name">The name of the destination file.</param> /// <param name="quality">The quality for JPEG encoding has to be in the range 0-100, /// where 100 is the best quality with the largest size.</param> /// <param name="saveToCameraRoll">If true the bitmap will be saved to the camera roll, otherwise it will be written to the default saved album.</param> public static Picture SaveToMediaLibrary(this WriteableBitmap bitmap, string name, int quality, bool saveToCameraRoll = false) { using (var stream = new MemoryStream()) { // Save the picture to the WP media library bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, quality); stream.Seek(0, SeekOrigin.Begin); var mediaLibrary = new MediaLibrary(); return(saveToCameraRoll ? mediaLibrary.SavePictureToCameraRoll(name, stream) : mediaLibrary.SavePicture(name, stream)); } }
// Сохранить private void AppSave_Click(object sender, EventArgs e) { if (AppHelper.IsTrial) { MessageBox.Show("Данная функция доступна в полной версии программы", "Сохранить совет в виде изображения", MessageBoxButton.OK); } else { var streamResourceInfo = Application.GetResourceStream(new Uri("Background.png", UriKind.Relative)); var image = new BitmapImage(); image.SetSource(streamResourceInfo.Stream); var writeableBitmap = new WriteableBitmap(image); var bitmap = new BitmapImage(_bitmapImage.UriSource); var im = new Image() { Width = 480, Height = 350, Source = bitmap, Stretch = Stretch.Fill }; var textBlockTitle = new TextBlock { FontSize = 28, Width = 200, Height = 60, FontWeight = FontWeights.Bold, TextAlignment = TextAlignment.Right, TextWrapping = TextWrapping.Wrap, Foreground = new SolidColorBrush(Color.FromArgb(210, 210, 210, 210)), Text = "СОВЕТ #" + AppHelper.PageIndex, }; var textBlockText = new TextBlock { FontSize = 26, Width = 470, Height = 450, TextAlignment = TextAlignment.Center, TextWrapping = TextWrapping.Wrap, FontWeight = FontWeights.Bold, Foreground = new SolidColorBrush(Color.FromArgb(210, 210, 210, 210)), Text = BaseLineDB.ResourceManager.GetString("String" + AppHelper.PageIndex), }; writeableBitmap.Render(textBlockTitle, new TranslateTransform { X = 270, Y = 8, }); writeableBitmap.Render(textBlockText, new TranslateTransform { X = 5, Y = 400, }); MessageBox.Show("Совет сохранен в библиотеку фотографий.", "Выполнено", MessageBoxButton.OK); writeableBitmap.Render(im, new TranslateTransform { X = 0, Y = 40, }); writeableBitmap.Invalidate(); using (var mediaLibrary = new MediaLibrary()) { using (var stream = new MemoryStream()) { writeableBitmap.SaveJpeg(stream, writeableBitmap.PixelWidth, writeableBitmap.PixelHeight, 0, 100); stream.Seek(0, SeekOrigin.Begin); mediaLibrary.SavePicture("Cовет_" + AppHelper.PageIndex + ".jpg", stream); } } } }
/// <summary> /// Save picture to pictures hub. /// </summary> public void SaveToPicturesHub(CapturedPictureViewModel picture) { var mediaLibrary = new MediaLibrary(); mediaLibrary.SavePicture(picture.FileName, picture.ImageBytes); }
void generationWorker_DoWork(object sender, DoWorkEventArgs e) { int index = (int)e.Argument; DateTime now = DateTime.Now; string photoName = String.Format("daily_{0}.jpg", now.Ticks); Dispatcher.BeginInvoke(() => { using (MemoryStream stream = new MemoryStream()) { Stream bgStream = Application.GetResourceStream(new Uri(String.Format("Assets/CalendarTemplate/{0}.jpg", index), UriKind.Relative)).Stream; var container = new StackPanel() { Width = Constant.GENERATED_IMAGE_WIDTH, Height = Constant.GENERATED_IMAGE_HEIGHT, Background = new ImageBrush() { ImageSource = PictureDecoder.DecodeJpeg(bgStream, Constant.GENERATED_IMAGE_WIDTH, Constant.GENERATED_IMAGE_HEIGHT) } }; bgStream.Close(); var marginLeft = 20; var marginTop = 50; var offset = 25; var imageContainer = new Canvas() { Width = Constant.GENERATED_CALENDAR_WIDTH + offset * 2, Height = Constant.GENERATED_IMAGE_HEIGHT, Background = new SolidColorBrush(Colors.Transparent), Margin = new Thickness(marginLeft, 0, 0, 0), HorizontalAlignment = HorizontalAlignment.Left }; var opacityBorder = new Border() { Width = Constant.GENERATED_CALENDAR_WIDTH + offset * 2, Height = Constant.GENERATED_IMAGE_HEIGHT, Background = new SolidColorBrush(Colors.Black), Opacity = 0.5 }; var calendar = new CalendarForRender() { DataContext = App.ViewModelData, Width = Constant.GENERATED_CALENDAR_WIDTH, Margin = new Thickness(offset, marginTop, 0, 0) }; //calendar.Calendar.SelectedDate = DateTime.Now; calendar.Calendar.SelectedMonth = DateSelector.SelectedValue.Month; calendar.Calendar.SelectedYear = DateSelector.SelectedValue.Year; calendar.Calendar.Refresh(); imageContainer.Children.Add(opacityBorder); imageContainer.Children.Add(calendar); container.Children.Add(imageContainer); container.Measure(new Size(Constant.GENERATED_IMAGE_WIDTH, Constant.GENERATED_IMAGE_HEIGHT)); container.Arrange(new Rect(0, 0, Constant.GENERATED_IMAGE_WIDTH, Constant.GENERATED_IMAGE_HEIGHT)); var bitmap = new WriteableBitmap(container, null); bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100); stream.Seek(0, SeekOrigin.Begin); using (MediaLibrary library = new MediaLibrary()) { library.SavePicture(photoName, stream); } } }); }
public void onTaskCompleted(object sender, PhotoResult e) { var task = sender as ChooserBase <PhotoResult>; if (task != null) { task.Completed -= onTaskCompleted; } if (e.Error != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR)); return; } switch (e.TaskResult) { case TaskResult.OK: try { string imagePathOrContent = string.Empty; // Save image back to media library // only save to photoalbum if it didn't come from there ... if (cameraOptions.PictureSourceType == CAMERA && cameraOptions.SaveToPhotoAlbum) { MediaLibrary library = new MediaLibrary(); Picture pict = library.SavePicture(e.OriginalFileName, e.ChosenPhoto); // to save to photo-roll ... } int orient = ImageExifHelper.getImageOrientationFromStream(e.ChosenPhoto); int newAngle = 0; switch (orient) { case ImageExifOrientation.LandscapeLeft: newAngle = 90; break; case ImageExifOrientation.PortraitUpsideDown: newAngle = 180; break; case ImageExifOrientation.LandscapeRight: newAngle = 270; break; case ImageExifOrientation.Portrait: default: break; // 0 default already set } if (newAngle != 0) { using (Stream rotImageStream = ImageExifHelper.RotateStream(e.ChosenPhoto, newAngle)) { // we should reset stream position after saving stream to media library rotImageStream.Seek(0, SeekOrigin.Begin); if (cameraOptions.DestinationType == DATA_URL) { imagePathOrContent = GetImageContent(rotImageStream); } else // FILE_URL { imagePathOrContent = SaveImageToLocalStorage(rotImageStream, Path.GetFileName(e.OriginalFileName)); } } } else // no need to reorient { if (cameraOptions.DestinationType == DATA_URL) { imagePathOrContent = GetImageContent(e.ChosenPhoto); } else // FILE_URL { imagePathOrContent = SaveImageToLocalStorage(e.ChosenPhoto, Path.GetFileName(e.OriginalFileName)); } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, imagePathOrContent)); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error retrieving image.")); } break; case TaskResult.Cancel: DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Selection cancelled.")); break; default: DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Selection did not complete!")); break; } }
private void ImgBtnCapture_MouseLeftButtonUp(object sender, MouseButtonEventArgs e) { if ((Application.Current as App).TrialMode) { MessageBoxResult result = MessageBox.Show(AppResources.MessageBoxMessageImageSaveTrialVersionQuestion, AppResources.MessageBoxHeaderInfo, MessageBoxButton.OKCancel); if (result == MessageBoxResult.OK) { try { this.marketplaceDetailTask.Show(); } catch (Exception ex) { MessageBox.Show(AppResources.MessageBoxMessageMarketplaceOpenError + " " + ex.Message.ToString(), AppResources.MessageBoxHeaderError, MessageBoxButton.OK); } } } else { this.btmScreenshot = new WriteableBitmap((int)this.ToyGrid.ActualWidth, (int)this.ToyGrid.ActualHeight); this.btmScreenshot.Clear(Colors.Black); WriteableBitmap bmp_toy; var images = this.ToyGrid.Children.OfType <Image>(); List <Image> ImagesListScreen = new List <Image>(); foreach (var img in images) { int index = Canvas.GetZIndex(img); if (ImagesListScreen.Count == 0) { ImagesListScreen.Add(img); continue; } bool f_add = false; foreach (var img_list in ImagesListScreen) { int index_list = Canvas.GetZIndex(img_list); if (index <= index_list) { ImagesListScreen.Insert(ImagesListScreen.IndexOf(img_list), img); f_add = true; break; } } if (f_add == false) { ImagesListScreen.Add(img); } } foreach (var img in ImagesListScreen) { bmp_toy = new WriteableBitmap((int)(img.ActualWidth), (int)(img.ActualHeight)); bmp_toy.Render(img, new TranslateTransform() { X = 0, Y = 0 }); bmp_toy.Invalidate(); this.btmScreenshot.Blit(new Rect(img.Margin.Left, img.Margin.Top, img.ActualWidth, img.ActualHeight), bmp_toy, new Rect(0, 0, bmp_toy.PixelWidth, bmp_toy.PixelHeight)); //draw the frame } try { using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { string file_name = "image.jpg"; if (store.FileExists(file_name)) { store.DeleteFile(file_name); } using (IsolatedStorageFileStream stream = store.CreateFile(file_name)) { this.btmScreenshot.SaveJpeg(stream, this.btmScreenshot.PixelWidth, this.btmScreenshot.PixelHeight, 0, 100); } using (IsolatedStorageFileStream stream = store.OpenFile(file_name, FileMode.Open, FileAccess.Read)) { using (MediaLibrary library = new MediaLibrary()) { library.SavePicture(file_name, stream); } } store.DeleteFile(file_name); } MessageBox.Show(AppResources.MessageBoxMessageImageSavedInfo, AppResources.MessageBoxHeaderInfo, MessageBoxButton.OK); } catch (Exception ex) { MessageBox.Show(AppResources.MessageBoxMessageImageSaveError + " " + ex.Message.ToString(), AppResources.MessageBoxHeaderError, MessageBoxButton.OK); } } }
private async void AttemptSaveAsync() { if (!Processing) { Processing = true; AdaptButtonsToState(); GC.Collect(); var lowMemory = false; try { long result = (long)DeviceExtendedProperties.GetValue("ApplicationWorkingSetLimit"); lowMemory = result / 1024 / 1024 < 300; } catch (ArgumentOutOfRangeException) { } IBuffer buffer = null; Model.OriginalImage.Position = 0; using (var source = new StreamImageSource(Model.OriginalImage)) using (var segmenter = new InteractiveForegroundSegmenter(source)) using (var annotationsSource = new BitmapImageSource(Model.AnnotationsBitmap)) { segmenter.Quality = lowMemory ? 0.5 : 1; segmenter.AnnotationsSource = annotationsSource; var foregroundColor = Model.ForegroundBrush.Color; var backgroundColor = Model.BackgroundBrush.Color; segmenter.ForegroundColor = Windows.UI.Color.FromArgb(foregroundColor.A, foregroundColor.R, foregroundColor.G, foregroundColor.B); segmenter.BackgroundColor = Windows.UI.Color.FromArgb(backgroundColor.A, backgroundColor.R, backgroundColor.G, backgroundColor.B); using (var effect = new LensBlurEffect(source, new LensBlurPredefinedKernel(Model.KernelShape, (uint)Model.KernelSize))) using (var renderer = new JpegRenderer(effect)) { effect.KernelMap = segmenter; try { buffer = await renderer.RenderAsync(); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("AttemptSave rendering failed: " + ex.Message); } } } if (buffer != null) { using (var library = new MediaLibrary()) using (var stream = buffer.AsStream()) { library.SavePicture("lensblur_" + DateTime.Now.Ticks, stream); Model.Saved = true; AdaptButtonsToState(); } } Processing = false; AdaptButtonsToState(); } }
private void BtnSave_Click(object sender, RoutedEventArgs e) { Border b = new Border(); paint.Children.Remove(b); for (int i = 1; i <= 6; i++) { Uri uri = new Uri("/Document/9.jpg", UriKind.RelativeOrAbsolute); var image = new Image(); image.Stretch = Stretch.Fill; image.Source = new BitmapImage(uri); Canvas.SetTop(image, 0); Canvas.SetLeft(image, 0); paint.Children.Add(image); var image1 = new Image(); image1.Stretch = Stretch.Fill; image1.Source = new BitmapImage(new Uri("/Document/nec" + i.ToString() + ".png", UriKind.RelativeOrAbsolute)); image1.Width = PointX1 - PointX + 10; Canvas.SetTop(image1, PointY + 5); Canvas.SetLeft(image1, PointX + 5); //CompositeTransform MyTransform = new CompositeTransform(); //MyTransform.Rotation = (PointY1 - PointY) / 3; //image1.RenderTransform = MyTransform; paint.Children.Add(image1); WriteableBitmap wb = new WriteableBitmap(paint, null); wb.Render(paint, new TranslateTransform()); wb.Invalidate(); using (MemoryStream stream = new MemoryStream()) { WriteableBitmap bitmap = new WriteableBitmap(paint, null); bitmap.SaveJpeg(stream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100); stream.Seek(0, SeekOrigin.Begin); using (MediaLibrary mediaLibrary = new MediaLibrary()) { mediaLibrary.SavePicture("PictureJewelry" + i.ToString() + ".jpg", stream); } } } //MessageBox.Show("Picture Saved..."); //Stream st = new MemoryStream(); //BitmapImage b = new BitmapImage(); //b.UriSource = new Uri("/asstes/34.png", UriKind.Relative); //// encode writeablebitmap object to a jpeg stream. //Extensions.SaveJpeg(wb, st, 200, 250, 0, 100); //st.Close(); //Uri uri = new Uri("/Document/picture.jpg", UriKind.RelativeOrAbsolute); //BitmapImage bit = new BitmapImage(uri); //Stream stream = new MemoryStream(); //bit.SetSource(stream); //Extensions.SaveJpeg(wb, stream, 200, 250, 0, 100); //stream.Close(); //using (var isf = IsolatedStorageFile.GetUserStoreForApplication()) //{ // using (var fs = isf.CreateFile("picture.jpg")) // { // wb.SaveJpeg(fs, wb.PixelWidth, wb.PixelHeight, 10, 100); // } //} }
public void onCameraTaskCompleted(object sender, PhotoResult e) { if (e.Error != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR)); return; } switch (e.TaskResult) { case TaskResult.OK: try { string imagePathOrContent = string.Empty; if (cameraOptions.DestinationType == FILE_URI) { // Save image in media library if (cameraOptions.SaveToPhotoAlbum) { MediaLibrary library = new MediaLibrary(); Picture pict = library.SavePicture(e.OriginalFileName, e.ChosenPhoto); // to save to photo-roll ... } int orient = ImageExifHelper.getImageOrientationFromStream(e.ChosenPhoto); int newAngle = 0; switch (orient) { case ImageExifOrientation.LandscapeLeft: newAngle = 90; break; case ImageExifOrientation.PortraitUpsideDown: newAngle = 180; break; case ImageExifOrientation.LandscapeRight: newAngle = 270; break; case ImageExifOrientation.Portrait: default: break; // 0 default already set } Stream rotImageStream = ImageExifHelper.RotateStream(e.ChosenPhoto, newAngle); // we should return stream position back after saving stream to media library rotImageStream.Seek(0, SeekOrigin.Begin); WriteableBitmap image = PictureDecoder.DecodeJpeg(rotImageStream); imagePathOrContent = this.SaveImageToLocalStorage(image, Path.GetFileName(e.OriginalFileName)); } else if (cameraOptions.DestinationType == DATA_URL) { imagePathOrContent = this.GetImageContent(e.ChosenPhoto); } else { // TODO: shouldn't this happen before we launch the camera-picker? DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Incorrect option: destinationType")); return; } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, imagePathOrContent)); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error retrieving image.")); } break; case TaskResult.Cancel: DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Selection cancelled.")); break; default: DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Selection did not complete!")); break; } }
public void onTaskCompleted(object sender, PhotoResult e) { var task = sender as ChooserBase <PhotoResult>; if (task != null) { task.Completed -= onTaskCompleted; } if (e.Error != null) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR)); return; } switch (e.TaskResult) { case TaskResult.OK: try { string imagePathOrContent = string.Empty; // Save image back to media library // only save to photoalbum if it didn't come from there ... if (cameraOptions.PictureSourceType == CAMERA && cameraOptions.SaveToPhotoAlbum) { MediaLibrary library = new MediaLibrary(); Picture pict = library.SavePicture(e.OriginalFileName, e.ChosenPhoto); // to save to photo-roll ... } int newAngle = 0; // There's bug in Windows Phone 8.1 causing Seek on a DssPhotoStream not working properly. // https://connect.microsoft.com/VisualStudio/feedback/details/783252 // But a mis-oriented file is better than nothing, so try and catch. try { int orient = ImageExifHelper.getImageOrientationFromStream(e.ChosenPhoto); switch (orient) { case ImageExifOrientation.LandscapeLeft: newAngle = 90; break; case ImageExifOrientation.PortraitUpsideDown: newAngle = 180; break; case ImageExifOrientation.LandscapeRight: newAngle = 270; break; case ImageExifOrientation.Portrait: default: break; // 0 default already set } } catch { Debug.WriteLine("Error fetching orientation from Exif"); } if (newAngle != 0) { using (Stream rotImageStream = ImageExifHelper.RotateStream(e.ChosenPhoto, newAngle)) { // we should reset stream position after saving stream to media library rotImageStream.Seek(0, SeekOrigin.Begin); if (cameraOptions.DestinationType == DATA_URL) { imagePathOrContent = GetImageContent(rotImageStream); } else // FILE_URL or NATIVE_URI (both use the same resultant uri format) { imagePathOrContent = SaveImageToLocalStorage(rotImageStream, Path.GetFileName(e.OriginalFileName)); } } } else // no need to reorient { if (cameraOptions.DestinationType == DATA_URL) { imagePathOrContent = GetImageContent(e.ChosenPhoto); } else // FILE_URL or NATIVE_URI (both use the same resultant uri format) { imagePathOrContent = SaveImageToLocalStorage(e.ChosenPhoto, Path.GetFileName(e.OriginalFileName)); } } DispatchCommandResult(new PluginResult(PluginResult.Status.OK, imagePathOrContent)); } catch (Exception) { DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Error retrieving image.")); } break; case TaskResult.Cancel: DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Selection cancelled.")); break; default: DispatchCommandResult(new PluginResult(PluginResult.Status.ERROR, "Selection did not complete!")); break; } }
private void SaveButton_Click(object sender, EventArgs e) { if (this.editedBitmap != null) { if ((Application.Current as App).TrialMode) { MessageBoxResult result = MessageBoxResult.None; try { result = MessageBox.Show(AppResources.MessageBoxMessageTrialVersionQuestion, AppResources.MessageBoxHeaderInfo, MessageBoxButton.OKCancel); } catch (Exception) { result = MessageBoxResult.None; } if (result == MessageBoxResult.OK) { try { this.marketplaceDetailTask.Show(); } catch (Exception ex) { try { MessageBox.Show(AppResources.MessageBoxMessageMarketplaceOpenError + " " + ex.Message.ToString(), AppResources.MessageBoxHeaderError, MessageBoxButton.OK); } catch (Exception) { // Ignore } } } } else { try { using (IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication()) { string file_name = "image.jpg"; if (store.FileExists(file_name)) { store.DeleteFile(file_name); } using (IsolatedStorageFileStream stream = store.CreateFile(file_name)) { this.editedBitmap.SaveJpeg(stream, this.editedBitmap.PixelWidth, this.editedBitmap.PixelHeight, 0, 100); } using (IsolatedStorageFileStream stream = store.OpenFile(file_name, FileMode.Open, FileAccess.Read)) { using (MediaLibrary library = new MediaLibrary()) { library.SavePicture(file_name, stream); } } store.DeleteFile(file_name); } this.editedImageChanged = false; try { MessageBox.Show(AppResources.MessageBoxMessageImageSavedInfo, AppResources.MessageBoxHeaderInfo, MessageBoxButton.OK); } catch (Exception) { // Ignore } } catch (Exception ex) { try { MessageBox.Show(AppResources.MessageBoxMessageImageSaveError + " " + ex.Message.ToString(), AppResources.MessageBoxHeaderError, MessageBoxButton.OK); } catch (Exception) { // Ignore } } } } }
/// <summary> /// Saves an image to the media library. /// </summary> /// <param name="name">Name of the image file saved to the media library.</param> /// <param name="imageBuffer">Buffer that contains the image in the required JPEG file format.</param> public void SavePicture(string name, byte[] imageBuffer) { _mediaLibrary.SavePicture(name, imageBuffer); }