Image encoder for writing image data to a stream in png format.
Inheritance: IImageEncoder
		public override void LoadFileDialog(FolderLocations folderLocation, int maxWidth, int maxHeight, int x, int y, int width, int height, string[] fileTypes, StreamLoadedCallbackMethod streamLoadedCallback)
		{
			if (streamLoadedCallback == null) return;
			string filename = EditorUtility.OpenFilePanel("Load file", "", generateFilterValue(fileTypes));
			if (!string.IsNullOrEmpty(filename))
			{
				if (maxWidth == 0 || maxHeight == 0 || folderLocation != FolderLocations.Pictures)
				{
					streamLoadedCallback(new FileStream(filename, FileMode.Open, FileAccess.Read), true);
				}
				else
				{
					var newStream = new MemoryStream();
					try
					{
						using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
						{
							IImageDecoder decoder = null;
							switch (Path.GetExtension(filename).ToLower())
							{
								case ".jpg": decoder = new JpegDecoder(); break;
								case ".jpeg": decoder = new JpegDecoder(); break;
								case ".png": decoder = new PngDecoder(); break;
								default:
									Debug.LogError("Unsuported file ext type: " + Path.GetExtension(filename));
									streamLoadedCallback(null, false);
									return;
							}
							var image = new ExtendedImage();
							decoder.Decode(image, stream);
							var newSize = MathUtilities.FitInViewIfLarger(image.PixelWidth, image.PixelHeight, maxWidth, maxHeight);
							var newImage = ExtendedImage.Resize(image, (int)newSize.x, (int)newSize.y, new NearestNeighborResizer());

							var encoder = new PngEncoder();
							encoder.Encode(newImage, newStream);
							newStream.Position = 0;
						}
					}
					catch (Exception e)
					{
						newStream.Dispose();
						newStream = null;
						Debug.LogError(e.Message);
					}
					finally
					{
						streamLoadedCallback(newStream, true);
					}
				}
			}
			else
			{
				streamLoadedCallback(null, false);
			}
		}
Esempio n. 2
0
        public Uri ToUri()
        {
            this.Measure(new Size(173, 173));
            this.Arrange(new Rect(0, 0, 173, 173));

            ExtendedImage tileImaged = this.ToImage();

            Encoders.AddEncoder<PngEncoder>();

            var encoder = new PngEncoder();

            var filename = string.Format("/Shared/ShellContent/StatementFront{0}.png", Id);

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (!myIsolatedStorage.DirectoryExists("/Shared/ShellContent"))
                {
                    myIsolatedStorage.CreateDirectory("/Shared/ShellContent");
                }

                if (myIsolatedStorage.FileExists(filename))
                {
                    myIsolatedStorage.DeleteFile(filename);
                }

                IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(filename);
                encoder.Encode(tileImaged, fileStream);
                fileStream.Close();
            }

            return new Uri("isostore:" + filename, UriKind.RelativeOrAbsolute);
        }
Esempio n. 3
0
        public static void SaveImage(this UIElement uiElement)
        {
            var dialog = new SaveFileDialog
            {
                DefaultExt = ".png",
                Filter = "PNG | *.png | JPG | *.jpg",
            };
            var save = dialog.ShowDialog();
            if (save.HasValue && save.Value)
            {
                var saveStream = dialog.OpenFile();

                var bitmap = new WriteableBitmap(uiElement, new TranslateTransform());
                var image = bitmap.ToImage();
                if (dialog.SafeFileName.EndsWith(".png"))
                {
                    var encoder = new PngEncoder();
                    encoder.Encode(image, saveStream);
                }
                else if (dialog.SafeFileName.EndsWith(".jpg"))
                {
                    var encoder = new JpegEncoder();
                    encoder.Encode(image, saveStream);
                }

                saveStream.Close();
            }
        }
Esempio n. 4
0
 public static void SaveToPNG(this WriteableBitmap bitmap)//扩展WriteableBitmap类添加SaveToPNG方法
 {
     if (bitmap != null)
     {
         SaveFileDialog sfd = new SaveFileDialog
                                 {
                                      Filter = "PNG Files (*.png)|*.png|All Files (*.*)|*.*",
                                      DefaultExt = ".png",
                                      FilterIndex = 1
                                 };
         if ((bool)sfd.ShowDialog())
         {
             var img = bitmap.ToImage();
             var encoder = new PngEncoder();
             using (Stream stream = sfd.OpenFile())
             {
                 encoder.Encode(img, stream);
                 stream.Close();
             }
         }
     }
 }
Esempio n. 5
0
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "JPEGファイル (*.jpg)|*.jpg|PNGファイル (*.png)|*.png|ビットマップファイル (*.bmp)|*.bmp";
            if (sfd.ShowDialog() == true)
            {
                IImageEncoder enc;
                string fn = sfd.SafeFileName.ToLower();
                if(fn.EndsWith(".jpg"))
                {
                    enc = new JpegEncoder();
                }
                else if (fn.EndsWith(".png"))
                {
                    enc = new PngEncoder();
                }
                else if (fn.EndsWith(".bmp"))
                {
                    enc = new BmpEncoder();
                }
                else
                {
                    MessageBox.Show("エラー");
                    return;
                }

                double scaledWidth = (cropImage.Width * zoom);
                double scaledHeight = (cropImage.Height * zoom);
                double scaledLeft = (imageWidth - scaledWidth) / 2;
                double scaledTop = (imageHeight - scaledHeight) / 2;
                Rect r = new Rect((double)cropCanvas.GetValue(Canvas.LeftProperty), (double)cropCanvas.GetValue(Canvas.TopProperty), cropCanvas.Width, cropCanvas.Height);
                Rect r2 = new Rect(scaledLeft, scaledTop, scaledWidth , scaledHeight);
                r.Intersect(r2);
                double clipedLeft = r.Left - scaledLeft;
                double clipedTop = r.Top - scaledTop;
                r.X = clipedLeft;
                r.Y = clipedTop;
                ScaleTransform st = new ScaleTransform();
                st.ScaleX = zoom;
                st.ScaleY = zoom;
                WriteableBitmap wb = new WriteableBitmap(cropImage, st);
                WriteableBitmap outputWb = new WriteableBitmap((int)r.Width, (int)r.Height);
                outputWb.Blit(new Rect(0, 0, r.Width, r.Height), wb, new Rect(r.Left, r.Top, r.Width, r.Height));
                ImageTools.Image img = ToImage(outputWb);
                using (Stream stream = sfd.OpenFile())
                {
                    enc.Encode(img, stream);
                }
            }
        }
        private async Task SaveTheImage(WriteableBitmap bitmap)
        {
            if (await _storageService.FileExistsAsync(LockScreenFile))
            {
                await _storageService.DeleteFileAsync(LockScreenFile);
            }

            using (var fileStream = await _storageService.CreateFileAsync(LockScreenFile))
            {
                var encoder = new PngEncoder();
                var image = bitmap.ToImage();
                encoder.Encode(image, fileStream);
            }
        }
Esempio n. 7
0
        private ArticleImage CreateFakeArticleImage(Chapter chapter)
        {
            var image = new ArticleImage();
          //  image.Chapter = chapter;

            var bitMapImage = new BitmapImage();

            GifDecoder gd = new GifDecoder();
            var img = new ImageTools.ExtendedImage();

            gd.Decode(img, Application.GetResourceStream(
                new Uri("/SmartReader.Library;component/Resource/8004887.gif", UriKind.Relative)
                ).Stream);

            var png = new PngEncoder();
            BitmapImage bitmap = new BitmapImage();
            bitmap.CreateOptions = BitmapCreateOptions.None;
            using (MemoryStream stream = new MemoryStream())
            {
                png.Encode(img, stream);
                bitmap.SetSource(stream);
            }

            image.ImageBytes = ConvertToBytes(bitmap);
            Storage.SaveArticleImages(new[] { image });

            return image;
        }
Esempio n. 8
0
        /// <summary>
        /// Used to render the contents to a tile
        /// </summary>
        /// <returns>a <see cref="StandardTileData"/> with the contents of this control</returns>
        public StandardTileData ToTile()
        {
            // Need to call these, otherwise the contents aren't rendered correctly.
            this.Measure(new Size(173, 173));
            this.Arrange(new Rect(0, 0, 173, 173));

            // The png encoder is the work of the ImageTools API. http://imagetools.codeplex.com/
            ExtendedImage tileImaged = this.ToImage();

            Encoders.AddEncoder<PngEncoder>();

            var p = new PngEncoder();

            const string tempFileName = "/Shared/ShellContent/tileImage.png";

            using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (myIsolatedStorage.FileExists(tempFileName))
                {
                    myIsolatedStorage.DeleteFile(tempFileName);
                }

                IsolatedStorageFileStream fileStream = myIsolatedStorage.CreateFile(tempFileName);
                p.Encode(tileImaged, fileStream);
                fileStream.Close();
            }

            var newTile = new StandardTileData
            {
                Title = Title,
                BackgroundImage =
                    new Uri("isostore:" + tempFileName, UriKind.RelativeOrAbsolute)
            };

            return newTile;
        }
Esempio n. 9
0
        private void UploadImage(ExtendedImage image)
        {
            var webClient = new WebClient();
            webClient.OpenWriteCompleted += (sender, e) => {
                if (e.Error == null) {
                    var pngEncoder = new PngEncoder();
                    using (e.Result) {
                        pngEncoder.Encode(image, e.Result);
                    }
                }
            };

            webClient.WriteStreamClosed += (sender, e) => {
                if (e.Error == null) {
                    MessageBox.Show("Image uploaded successfully");
                }
            };

            webClient.OpenWriteAsync(new Uri("http://localhost:5637/Wafers/UploadImage", UriKind.Absolute), "POST");
        }
        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (checkBoxAttachScreenShot.IsChecked.HasValue && checkBoxAttachScreenShot.IsChecked.Value)
            {
                ImageTools.Image image = ImageTools.ImageExtensions.ToImage(_screenShot);

                using (MemoryStream writestream = new MemoryStream())
                {

                    PngEncoder encoder = new PngEncoder();
                    encoder.Encode(image, writestream);

                    byte[] bytes = writestream.ToArray();

                    MemoryStream readStream = new MemoryStream(bytes);

                    UploadFile(readStream);
                }

            }

            // always try to use {0} as newline

            string text = string.Format("Name: {1}{0}Contact: {2}{0}Comment: {3}{0}{0}{0}",
                Environment.NewLine,
                this.textBoxName.Text,
                this.textBoxContactInfo.Text,
                this.textBoxComments.Text);

            if (checkBoxAttachSysinfo.IsChecked.HasValue && checkBoxAttachSysinfo.IsChecked.Value)
            {
                text = string.Format("{1}{0}SysInfo:{0}{2}", Environment.NewLine, text, textBlockSysInfo.Text);
            }

            UploadSysInfo(text);

            this.DialogResult = true;
        }
Esempio n. 11
0
		public override void LoadFileDialog(FolderLocations folderLocation, int maxWidth, int maxHeight, int x, int y, int width, int height, string[] fileTypes, StreamLoadedCallbackMethod streamLoadedCallback)
		{
			if (streamLoadedCallback == null) return;

			// open native dlg
			var file = new OPENFILENAME();
			file.lStructSize = (uint)Marshal.SizeOf(typeof(OPENFILENAME));
			file.hwndOwner = IntPtr.Zero;
			file.lpstrDefExt = IntPtr.Zero;
			file.lpstrFile = Marshal.AllocHGlobal((int)MAX_PATH);
			unsafe {((byte*)file.lpstrFile.ToPointer())[0] = 0;}
			file.nMaxFile = MAX_PATH;
			file.lpstrFilter = generateFilterValue(fileTypes);
			file.nFilterIndex = 0;
			file.lpstrInitialDir = Marshal.StringToHGlobalUni(Application.dataPath);
			file.lpstrTitle = Marshal.StringToHGlobalUni("Load file");
			file.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR;
			GetOpenFileName(ref file);

			// get native dlg result
			string filename = null;
			if (file.lpstrFile != IntPtr.Zero)
			{
				filename = Marshal.PtrToStringUni(file.lpstrFile);
				Debug.Log("Loading file: " + filename);
			}

			Marshal.FreeHGlobal(file.lpstrFile);
			Marshal.FreeHGlobal(file.lpstrInitialDir);
			Marshal.FreeHGlobal(file.lpstrTitle);
			Marshal.FreeHGlobal(file.lpstrFilter);

			// open file
			if (!string.IsNullOrEmpty(filename))
			{
				if (maxWidth == 0 || maxHeight == 0 || folderLocation != FolderLocations.Pictures)
				{
					streamLoadedCallback(new FileStream(filename, FileMode.Open, FileAccess.Read), true);
				}
				else
				{
					var newStream = new MemoryStream();
					try
					{
						using (var stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
						{
							ImageTools.IO.IImageDecoder decoder = null;
							switch (Path.GetExtension(filename).ToLower())
							{
								case ".jpg": decoder = new ImageTools.IO.Jpeg.JpegDecoder(); break;
								case ".jpeg": decoder = new ImageTools.IO.Jpeg.JpegDecoder(); break;
								case ".png": decoder = new ImageTools.IO.Png.PngDecoder(); break;
								default:
									Debug.LogError("Unsuported file ext type: " + Path.GetExtension(filename));
									streamLoadedCallback(null, false);
									return;
							}
							var image = new ExtendedImage();
							decoder.Decode(image, stream);
							var newSize = Reign.MathUtilities.FitInViewIfLarger(image.PixelWidth, image.PixelHeight, maxWidth, maxHeight);
							var newImage = ExtendedImage.Resize(image, (int)newSize.x, (int)newSize.y, new NearestNeighborResizer());

							var encoder = new PngEncoder();
							encoder.Encode(newImage, newStream);
							newStream.Position = 0;
						}
					}
					catch (Exception e)
					{
						newStream.Dispose();
						newStream = null;
						Debug.LogError(e.Message);
					}
					finally
					{
						streamLoadedCallback(newStream, true);
					}
				}
			}
			else
			{
				streamLoadedCallback(null, false);
			}
		}
Esempio n. 12
0
        void FetchComicReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            // Clean the webclient that was created when this request was created.
            WebClient webClient = sender as WebClient;
            if (webClient != null)
            {
                webClient = null;
            }

            if (RESTError(e))
            {
                Debug.WriteLine("Error fetching comic image! Error: " + e.Error.ToString());
                return;
            }

            ComicItem currentComicModel = (ComicItem)e.UserState;
            Debug.WriteLine("Fetched comic strip image.");

            Stream reply = null;
            try
            {
                reply = (Stream)e.Result;
            }
            catch (WebException webEx)
            {
                if (webEx.Status != WebExceptionStatus.Success)
                {
                    Debug.WriteLine("Web error occured. Cannot load image!");
                    return;
                }
            }

            MemoryStream comicStripBytes = new MemoryStream();
            reply.CopyTo(comicStripBytes);
            byte[] imgBytes = comicStripBytes.ToArray();
            if (isGifImage(imgBytes))
            {
                Debug.WriteLine("Image is a GIF");

                ExtendedImage gifStrip = new ExtendedImage();
                gifStrip.LoadingCompleted +=
                    (s, args) => {
                        Debug.WriteLine("GIF loaded. Encoding GIF image to PNG image...");

                        ExtendedImage gifImage = (ExtendedImage)s;
                        MemoryStream pngBytes = new MemoryStream();

                        ImageTools.IO.Png.PngEncoder enc = new PngEncoder();
                        enc.Encode(gifImage, pngBytes);

                        this.Dispatcher.BeginInvoke(() => {
                            Debug.WriteLine("Encoding done. Setting PNG bytes to BitmapImage and showing.");
                            showNewComic(currentComicModel, pngBytes);
                        });
                    };

                gifStrip.UriSource = new Uri(currentComicModel.imageUrl,
                                             UriKind.Absolute);
            }
            else
            {
                Debug.WriteLine("Image is not a GIF. Putting image bytes directly to BitmapImage.");
                showNewComic(currentComicModel, comicStripBytes);
            }

            App.comicListModel.ComicLoading = false;
        }