Ejemplo n.º 1
0
        public MemBitmap LoadImage(Stream input, OutputImageFormat format)
        {
            ImageTools.ExtendedImage extendedImg = new ImageTools.ExtendedImage();
            //TODO: review img loading, we should not use only its extension
            switch (format)
            {
            case OutputImageFormat.Jpeg:
            {
                var decoder = new ImageTools.IO.Jpeg.JpegDecoder();
                var dst     = new JpegDecoderDst();
                extendedImg.JpegDecompressDest = dst;
                extendedImg.Load(input, decoder);
                //copy from

                return(dst.MemBitmapOutput);
            }
            break;

            case OutputImageFormat.Png:
            {
                var decoder = new ImageTools.IO.Png.PngDecoder();
                extendedImg.Load(input, decoder);
            }
            break;

            default:
                throw new System.NotSupportedException();
            }

            //assume 32 bit ??
            byte[] pixels = extendedImg.Pixels;
            unsafe
            {
                fixed(byte *p_src = &pixels[0])
                {
                    PixelFarm.CpuBlit.MemBitmap memBmp = PixelFarm.CpuBlit.MemBitmap.CreateFromCopy(
                        extendedImg.PixelWidth,
                        extendedImg.PixelHeight,
                        (IntPtr)p_src,
                        pixels.Length,
                        false
                        );

                    memBmp.IsBigEndian = true;
                    return(memBmp);
                }
            }

            ////PixelFarm.CpuBlit.MemBitmap memBmp = PixelFarm.CpuBlit.MemBitmap.CreateFromCopy(
            ////    extendedImg.PixelWidth,
            ////    extendedImg.PixelHeight,
            ////    extendedImg.PixelWidth * 4, //assume
            ////    32, //assume?
            ////    extendedImg.Pixels,
            ////    false
            ////    );
            ////the imgtools load data as BigEndian
            //memBmp.IsBigEndian = true;
            //return memBmp;
        }
Ejemplo n.º 2
0
        static PixelFarm.Agg.ActualImage LoadImage(string filename)
        {
            ImageTools.ExtendedImage extendedImg = new ImageTools.ExtendedImage();
            using (var fs = new System.IO.FileStream(filename, System.IO.FileMode.Open, System.IO.FileAccess.Read))
            {
                //TODO: review img loading, we should not use only its extension
                //
                string fileExt = System.IO.Path.GetExtension(filename).ToLower();
                switch (fileExt)
                {
                case ".png":
                {
                    var decoder = new ImageTools.IO.Png.PngDecoder();
                    extendedImg.Load(fs, decoder);
                }
                break;

                case ".jpg":
                {
                    var decoder = new ImageTools.IO.Jpeg.JpegDecoder();
                    extendedImg.Load(fs, decoder);
                }
                break;

                default:
                    throw new System.NotSupportedException();
                }
                //var decoder = new ImageTools.IO.Png.PngDecoder();
            }
            //assume 32 bit

            PixelFarm.Agg.ActualImage actualImg = PixelFarm.Agg.ActualImage.CreateFromBuffer(
                extendedImg.PixelWidth,
                extendedImg.PixelHeight,
                PixelFarm.Agg.PixelFormat.ARGB32,
                extendedImg.Pixels32
                );
            //the imgtools load data as BigEndian
            actualImg.IsBigEndian = true;
            return(actualImg);
        }
Ejemplo n.º 3
0
        public MemBitmap LoadImage(Stream input, OutputImageFormat format)
        {
            ImageTools.ExtendedImage extendedImg = new ImageTools.ExtendedImage();
            //TODO: review img loading, we should not use only its extension
            switch (format)
            {
            case OutputImageFormat.Png:
            {
                var decoder = new ImageTools.IO.Png.PngDecoder();
                extendedImg.Load(input, decoder);
            }
            break;

            case OutputImageFormat.Jpeg:
            {
                var decoder = new ImageTools.IO.Jpeg.JpegDecoder();
                extendedImg.Load(input, decoder);
            }
            break;

            default:
                throw new System.NotSupportedException();
            }
            //var decoder = new ImageTools.IO.Png.PngDecoder();


            //assume 32 bit

            PixelFarm.CpuBlit.MemBitmap memBmp = PixelFarm.CpuBlit.MemBitmap.CreateFromCopy(
                extendedImg.PixelWidth,
                extendedImg.PixelHeight,
                extendedImg.Pixels32
                );
            //the imgtools load data as BigEndian
            memBmp.IsBigEndian = true;
            return(memBmp);
        }
Ejemplo n.º 4
0
        private void ParseImg(HtmlNode htmlNode, ref List <Elements.BaseElement> elements)
        {
            string path = _ePubViewer.Book.GetFilePath(HttpUtility.UrlDecode(htmlNode.Attributes["src"].Value.Replace("../", "")));

            if (path == null) // img src file does not exists (don't render)
            {
                Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "Warning: EPubReader.Parseer.ParseImg - Image \"{0}\" does not exists.", HttpUtility.UrlDecode(htmlNode.Attributes["src"].Value.Replace("../", ""))));
                return;
            }

            Stream s = IsolatedStorageHelper.ReadZipStream(path);

            string fileName = Guid.NewGuid().ToString();
            Size   size     = Size.Empty;

            // detect image type
            if (
                path.EndsWith(".jpg", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".jpeg", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".jpe", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".jif", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".jfif", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".jfi", StringComparison.OrdinalIgnoreCase)
                )
            {
                BitmapSource bs = new BitmapImage();
                bs.SetSource(s);

                size = new Size(bs.PixelWidth, bs.PixelHeight);

                // save image
                fileName += ".jpg";
                string isfPath = Path.Combine(_ePubViewer.Book.GetImagesDirectory(), fileName);
                try
                {
                    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!isf.DirectoryExists(Path.GetDirectoryName(isfPath)))
                        {
                            isf.CreateDirectory(Path.GetDirectoryName(isfPath));
                        }

                        using (IsolatedStorageFileStream isfs = isf.CreateFile(isfPath))
                        {
                            WriteableBitmap wb = new WriteableBitmap(bs);
                            wb.SaveJpeg(isfs, bs.PixelWidth, bs.PixelHeight, 0, 100);
                            isfs.Close();
                        }
                    }
                }
                catch
                {
                    Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "Warning: EPubReader.Parseer.ParseImg - Error saving image \"{0}\".", isfPath));
                    return;
                }
            }
            else if (
                path.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".dib", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".gif", StringComparison.OrdinalIgnoreCase)
                ||
                path.EndsWith(".png", StringComparison.OrdinalIgnoreCase)
                )
            {
                ImageTools.ExtendedImage    extendedImage = new ImageTools.ExtendedImage();
                ImageTools.IO.IImageDecoder decoder;

                if (
                    path.EndsWith(".bmp", StringComparison.OrdinalIgnoreCase)
                    ||
                    path.EndsWith(".dib", StringComparison.OrdinalIgnoreCase)
                    )
                {
                    decoder = new ImageTools.IO.Bmp.BmpDecoder();
                }
                else if (path.EndsWith(".gif", StringComparison.OrdinalIgnoreCase))
                {
                    decoder = new ImageTools.IO.Gif.GifDecoder();
                }
                else // if (path.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
                {
                    decoder = new ImageTools.IO.Png.PngDecoder();
                }

                decoder.Decode(extendedImage, s);

                size = new Size(extendedImage.PixelWidth, extendedImage.PixelHeight);

                ImageTools.IO.Png.PngEncoder pngEncoder = new ImageTools.IO.Png.PngEncoder();

                // save image
                fileName += ".png";
                string isfPath = Path.Combine(_ePubViewer.Book.GetImagesDirectory(), fileName);
                try
                {
                    using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
                    {
                        if (!isf.DirectoryExists(Path.GetDirectoryName(isfPath)))
                        {
                            isf.CreateDirectory(Path.GetDirectoryName(isfPath));
                        }

                        using (IsolatedStorageFileStream isfs = isf.CreateFile(isfPath))
                        {
                            pngEncoder.Encode(extendedImage, isfs);
                            isfs.Close();
                        }
                    }
                }
                catch
                {
                    Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "Warning: EPubReader.Parseer.ParseImg - Error saving image \"{0}\".", isfPath));
                    return;
                }
            }
            else
            {
                s.Close();
                s.Dispose();

                Debug.WriteLine(String.Format(CultureInfo.InvariantCulture, "Warning: EPubReader.Parseer.ParseImg - Not recognizable image type \"{0}\".", path));
                return;
            }

            RemoveLastBreak(ref elements);

            // add image
            Elements.BaseElement element = new Elements.Image()
            {
                FileName = fileName,
                Width    = (int)size.Width,
                Height   = (int)size.Height
            };

            ExtractId(htmlNode, ref element);

            elements.Add(element);
        }
Ejemplo n.º 5
0
        private static void waitAndProcessImage(string[] fileTypes, string[] dataPathPatterns, int maxWidth, int maxHeight, StreamLoadedCallbackMethod streamLoadedCallback)
        {
            // wait for event
            while (true)
            {
                IntPtr _event = IntPtr.Zero;
                Common.bps_get_event(ref _event, -1);                // wait here for next event
                if (_event != IntPtr.Zero)
                {
                    if (Common.bps_event_get_code(_event) == NAVIGATOR_CHILD_CARD_CLOSED)
                    {
                        IntPtr reasonPtr = Common.navigator_event_get_card_closed_reason(_event);
                        string reason    = Marshal.PtrToStringAnsi(reasonPtr);
                        Debug.Log("reason: " + reason);
                        if (reason == "save")                        //save - cancel
                        {
                            IntPtr dataPathPtr = Common.navigator_event_get_card_closed_data(_event);
                            string dataPath    = Marshal.PtrToStringAnsi(dataPathPtr);
                            Debug.Log("Loading file from dataPath: " + dataPath);

                            try
                            {
                                System.Text.RegularExpressions.MatchCollection matches = null;
                                foreach (var pattern in dataPathPatterns)
                                {
                                    matches = System.Text.RegularExpressions.Regex.Matches(dataPath, pattern);
                                    if (matches.Count != 0)
                                    {
                                        break;
                                    }
                                }

                                if (matches != null)
                                {
                                    foreach (System.Text.RegularExpressions.Match match in matches)
                                    {
                                        if (match.Groups.Count == 3)
                                        {
                                            string path     = match.Groups[1].Value;
                                            string fileName = match.Groups[2].Value;

                                            // check for valid file type
                                            bool pass = false;
                                            foreach (var type in fileTypes)
                                            {
                                                if (Path.GetExtension(fileName) == type)
                                                {
                                                    pass = true;
                                                    break;
                                                }
                                            }
                                            if (!pass)
                                            {
                                                throw new Exception("Invalid file ext.");
                                            }

                                            // load file
                                            MemoryStream stream = null;
                                            using (var file = new FileStream(path + fileName, FileMode.Open, FileAccess.Read))
                                            {
                                                if (maxWidth != 0 && maxHeight != 0)
                                                {
                                                    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 ImageTools.ExtendedImage();
                                                    decoder.Decode(image, file);
                                                    var newSize  = MathUtilities.FitInViewIfLarger(image.PixelWidth, image.PixelHeight, maxWidth, maxHeight);
                                                    var newImage = ImageTools.ExtendedImage.Resize(image, (int)newSize.x, (int)newSize.y, new ImageTools.Filtering.NearestNeighborResizer());
                                                    var encoder  = new ImageTools.IO.Jpeg.JpegEncoder();
                                                    stream = new MemoryStream();
                                                    encoder.Encode(newImage, stream);
                                                    stream.Position = 0;

                                                    /*unsafe
                                                     * {
                                                     *      IntPtr ilib = IntPtr.Zero;
                                                     *      if (img_lib_attach(&ilib) != 0)
                                                     *      {
                                                     *              Debug.LogError("Failed: img_lib_attach");
                                                     *              streamLoadedCallback(null, false);
                                                     *              return;
                                                     *      }
                                                     *
                                                     *      img_t image = new img_t();
                                                     *      image.flags = 0x00000002;
                                                     *      image.format = 32 | 0x00000100 | 0x00001000;
                                                     *      img_decode_callouts_t callouts = new img_decode_callouts_t();
                                                     *      if (img_load_file(ilib, "file://"+path+fileName, &callouts, &image) != 0)
                                                     *      {
                                                     *              img_t newImage = new img_t();
                                                     *              if (img_resize_fs(&image, &newImage) != 0)
                                                     *              {
                                                     *                      Debug.LogError("Failed: img_resize_fs");
                                                     *                      streamLoadedCallback(null, false);
                                                     *                      return;
                                                     *              }
                                                     *
                                                     *              Debug.Log("WIDTH: " + image.w);
                                                     *              Debug.Log("HEIGHT: " + image.h);
                                                     *              streamLoadedCallback(null, false);
                                                     *              return;
                                                     *              //byte* data = (byte*)newImage.data.ToPointer();
                                                     *              //byte[] managedData = new byte[newImage.stride];
                                                     *
                                                     *              //stream = new MemoryStream();
                                                     *      }
                                                     *      else
                                                     *      {
                                                     *              Debug.LogError("Failed to load image file: " + path + fileName);
                                                     *              streamLoadedCallback(null, false);
                                                     *              return;
                                                     *      }
                                                     *
                                                     *      img_lib_detach(ilib);
                                                     * }*/
                                                }
                                                else
                                                {
                                                    var data = new byte[file.Length];
                                                    file.Read(data, 0, data.Length);
                                                    stream          = new MemoryStream(data);
                                                    stream.Position = 0;
                                                }
                                            }

                                            streamLoadedCallback(stream, true);
                                            return;
                                        }
                                        else
                                        {
                                            throw new Exception("Invalid dataPath.");
                                        }
                                    }
                                }
                            }
                            catch (Exception e)
                            {
                                Debug.LogError(e.Message);
                            }

                            streamLoadedCallback(null, false);
                        }
                        else
                        {
                            streamLoadedCallback(null, false);
                        }

                        break;
                    }
                }
            }
        }
Ejemplo n.º 6
0
		private static void waitAndProcessImage(string[] fileTypes, string[] dataPathPatterns, int maxWidth, int maxHeight, StreamLoadedCallbackMethod streamLoadedCallback)
		{
			// wait for event
			while (true)
			{
				IntPtr _event = IntPtr.Zero;
				Common.bps_get_event(ref _event, -1);// wait here for next event
				if (_event != IntPtr.Zero)
				{
					if (Common.bps_event_get_code(_event) == NAVIGATOR_CHILD_CARD_CLOSED)
					{
						IntPtr reasonPtr = Common.navigator_event_get_card_closed_reason(_event);
						string reason = Marshal.PtrToStringAnsi(reasonPtr);
						Debug.Log("reason: " + reason);
						if (reason == "save")//save - cancel
						{
							IntPtr dataPathPtr = Common.navigator_event_get_card_closed_data(_event);
							string dataPath = Marshal.PtrToStringAnsi(dataPathPtr);
							Debug.Log("Loading file from dataPath: " + dataPath);
						
							try
							{
								System.Text.RegularExpressions.MatchCollection matches = null;
								foreach (var pattern in dataPathPatterns)
								{
									matches = System.Text.RegularExpressions.Regex.Matches(dataPath, pattern);
									if (matches.Count != 0) break;
								}

								if (matches != null)
								foreach (System.Text.RegularExpressions.Match match in matches)
								{
									if (match.Groups.Count == 3)
									{
										string path = match.Groups[1].Value;
										string fileName = match.Groups[2].Value;
									
										// check for valid file type
										bool pass = false;
										foreach (var type in fileTypes)
										{
											if (Path.GetExtension(fileName) == type)
											{
												pass = true;
												break;
											}
										}
										if (!pass) throw new Exception("Invalid file ext.");
									
										// load file
										MemoryStream stream = null;
										using (var file = new FileStream(path+fileName, FileMode.Open, FileAccess.Read))
										{
											if (maxWidth != 0 && maxHeight != 0)
											{
												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 ImageTools.ExtendedImage();
												decoder.Decode(image, file);
												var newSize = MathUtilities.FitInViewIfLarger(image.PixelWidth, image.PixelHeight, maxWidth, maxHeight);
												var newImage = ImageTools.ExtendedImage.Resize(image, (int)newSize.x, (int)newSize.y, new ImageTools.Filtering.NearestNeighborResizer());
												var encoder = new ImageTools.IO.Jpeg.JpegEncoder();
												stream = new MemoryStream();
												encoder.Encode(newImage, stream);
												stream.Position = 0;

												/*unsafe
												{
													IntPtr ilib = IntPtr.Zero;
													if (img_lib_attach(&ilib) != 0)
													{
														Debug.LogError("Failed: img_lib_attach");
														streamLoadedCallback(null, false);
														return;
													}

													img_t image = new img_t();
													image.flags = 0x00000002;
													image.format = 32 | 0x00000100 | 0x00001000;
													img_decode_callouts_t callouts = new img_decode_callouts_t();
													if (img_load_file(ilib, "file://"+path+fileName, &callouts, &image) != 0)
													{
														img_t newImage = new img_t();
														if (img_resize_fs(&image, &newImage) != 0)
														{
															Debug.LogError("Failed: img_resize_fs");
															streamLoadedCallback(null, false);
															return;
														}

														Debug.Log("WIDTH: " + image.w);
														Debug.Log("HEIGHT: " + image.h);
														streamLoadedCallback(null, false);
														return;
														//byte* data = (byte*)newImage.data.ToPointer();
														//byte[] managedData = new byte[newImage.stride];

														//stream = new MemoryStream();
													}
													else
													{
														Debug.LogError("Failed to load image file: " + path + fileName);
														streamLoadedCallback(null, false);
														return;
													}

													img_lib_detach(ilib);
												}*/
											}
											else
											{
												var data = new byte[file.Length];
												file.Read(data, 0, data.Length);
												stream = new MemoryStream(data);
												stream.Position = 0;
											}
										}

										streamLoadedCallback(stream, true);
										return;
									}
									else
									{
										throw new Exception("Invalid dataPath.");
									}
								}
							}
							catch (Exception e)
							{
								Debug.LogError(e.Message);
							}
						
							streamLoadedCallback(null, false);
						}
						else
						{
							streamLoadedCallback(null, false);
						}
					
						break;
					}
				}
			}
		}