示例#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;
        }
示例#2
0
        public static Image FromFile(string filename)
        {
            //TODO: review here
            //should not depend on the extension
            string fileext = IO.Path.GetExtension(filename).ToLower();

            switch (fileext)
            {
            default:
                throw new NotSupportedException();

            case ".jpg":
            {
                JpegDecoder jpegDec = new JpegDecoder();
                ImageTools.ExtendedImage outputImg = new ImageTools.ExtendedImage();
                using (System.IO.FileStream fs = new IO.FileStream(filename, IO.FileMode.Open))
                {
                    jpegDec.Decode(outputImg, fs);
                }
                //return bitmap
                return(new Bitmap(outputImg.PixelWidth, outputImg.PixelHeight, outputImg.Pixels,
                                  outputImg.DensityXInt32, outputImg.DensityYInt32));
            }

            case ".gif":
            {
                GifDecoder gifDec = new GifDecoder();
                ImageTools.ExtendedImage outputImg = new ImageTools.ExtendedImage();
                using (System.IO.FileStream fs = new IO.FileStream(filename, IO.FileMode.Open))
                {
                    gifDec.Decode(outputImg, fs);
                }
                //return bitmap
                return(new Bitmap(outputImg.PixelWidth, outputImg.PixelHeight, outputImg.Pixels,
                                  outputImg.DensityXInt32, outputImg.DensityYInt32));
            }

            case ".png":
            {
                ImageTools.IO.Png.PngDecoder pngDecoder = new PngDecoder();
                //HjgPngDecoder pngDecoder = new HjgPngDecoder();
                //PngDecoder pngDecoder = new PngDecoder();
                ImageTools.ExtendedImage outputImg = new ImageTools.ExtendedImage();
                using (System.IO.FileStream fs = new IO.FileStream(filename, IO.FileMode.Open))
                {
                    pngDecoder.Decode(outputImg, fs);
                }

                Bitmap bmp = new Bitmap(outputImg.PixelWidth,
                                        outputImg.PixelHeight, outputImg.Pixels,
                                        outputImg.DensityXInt32, outputImg.DensityYInt32);
                bmp.PixelFormat = Imaging.PixelFormat.Format32bppArgb;
                return(bmp);
            }
            }
            return(null);
        }
示例#3
0
 private void ShowVerifyCodeInput(string imgUrl)
 {
     Dispatcher.BeginInvoke(() =>
     {
         VerifyCodeStack.Visibility = Visibility.Visible;
         ImageTools.IO.Decoders.AddDecoder <GifDecoder>();
         ImageTools.IO.Decoders.AddDecoder <BmpDecoder>();
         ImageTools.IO.Decoders.AddDecoder <JpegDecoder>();
         ImageTools.IO.Decoders.AddDecoder <PngDecoder>();
         ImageTools.ExtendedImage img = new ImageTools.ExtendedImage();
         img.UriSource          = new Uri(imgUrl, UriKind.RelativeOrAbsolute);
         VerifyCodeImage.Source = img;
     });
 }
示例#4
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);
        }
示例#5
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);
        }
示例#6
0
        private void MakePdf(List <ImageTools.ExtendedImage> imgList, List <ImageTools.ExtendedImage> bpImgList)
        {
            var document = new PdfDocument();

            // UitvoerCreator uitvoercreator = new UitvoerCreator();
            foreach (var img in imgList)
            {
                PdfPage page = document.AddPage();
                page.Width  = 797;
                page.Height = 1123;
                XGraphics gfx = null;
                UIThread.Invoke(() => { gfx = XGraphics.FromPdfPage(page); });
                while (gfx == null)
                {
                    System.Threading.Thread.Sleep(100);
                }
                using (MemoryStream mstream = new MemoryStream())
                {
                    //var img = UitvoerView.GetImg();
                    if (img != null)
                    {
                        img.DensityX = 300;
                        img.DensityY = 300;
                        JpegEncoder encoder = new JpegEncoder();
                        encoder.Encode(img, mstream);
                        MemoryStream mss = new MemoryStream(mstream.ToArray());
                        mss.Seek(0, SeekOrigin.Begin);
                        //JpegEncoder encoder = new JpegEncoder();
                        //encoder.Encode(img, mstream);
                        //mstream.Seek(0, SeekOrigin.Begin);
                        //XImage.FromStream(ms);
                        XImage pdfImg = null;
                        UIThread.Invoke(() => { pdfImg = XImage.FromStream(mss); });
                        while (pdfImg == null)
                        {
                            System.Threading.Thread.Sleep(100);
                        }
                        pdfImg.Interpolate = false;
                        //gfx.DrawImage(pdfImg, 0, 0);
                        gfx.DrawImage(pdfImg, 0, 0, 797, 1123);
                    }
                }
            }

            PdfPage page2 = document.AddPage();

            page2.Width  = 797;
            page2.Height = 1123;

            XGraphics gfx2 = null;

            UIThread.Invoke(() => { gfx2 = XGraphics.FromPdfPage(page2); });
            while (gfx2 == null)
            {
                System.Threading.Thread.Sleep(100);
            }
            using (MemoryStream mstream2 = new MemoryStream())
            {
                ImageTools.ExtendedImage img2 = null;
                UIThread.Invoke(() => { img2 = UitvoerPrijsView.GetImg(SaveNeeded, PrintDatum); });
                while (img2 == null)
                {
                    System.Threading.Thread.Sleep(100);
                }

                img2.DensityX = 900;
                img2.DensityY = 900;
                JpegEncoder encoder2 = new JpegEncoder();
                encoder2.Quality = 100;
                encoder2.Encode(img2, mstream2);
                MemoryStream mss2 = new MemoryStream(mstream2.ToArray());
                mss2.Seek(0, SeekOrigin.Begin);
                XImage pdfImg2 = null;
                UIThread.Invoke(() => { pdfImg2 = XImage.FromStream(mss2); });
                while (pdfImg2 == null)
                {
                    System.Threading.Thread.Sleep(100);
                }
                pdfImg2.Interpolate = false;
                gfx2.DrawImage(pdfImg2, 0, 0, 797, 1123);
            }

            foreach (var img in bpImgList)
            {
                using (MemoryStream msb = new MemoryStream())
                {
                    PdfPage pageb = document.AddPage();
                    pageb.Width  = 797;
                    pageb.Height = 1123;
                    XGraphics gfxb = null;
                    UIThread.Invoke(() => { gfxb = XGraphics.FromPdfPage(pageb); });
                    while (gfxb == null)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    img.DensityX = 300;
                    img.DensityY = 300;
                    JpegEncoder encoderb = new JpegEncoder();
                    encoderb.Encode(img, msb);
                    MemoryStream msb2 = new MemoryStream(msb.ToArray());
                    msb2.Seek(0, SeekOrigin.Begin);
                    XImage pdfImg = null;
                    UIThread.Invoke(() => { pdfImg = XImage.FromStream(msb2); });
                    while (pdfImg == null)
                    {
                        System.Threading.Thread.Sleep(100);
                    }
                    pdfImg.Interpolate = false;
                    gfxb.DrawImage(pdfImg, 0, 0, 797, 1123);
                }
            }
            _File = document;

            /* foreach (var Img in uitvoercreator.MaakPlattegrondUitvoer())
             * {
             * PdfPage page3 = document.AddPage();
             * page3.Width = 797;
             * page3.Height = 1123;
             * XGraphics gfx3 = XGraphics.FromPdfPage(page3);
             * using (MemoryStream mstream3 = new MemoryStream())
             * {
             *    if (Img != null)
             *    {
             *        Img.DensityX = 300;
             *        Img.DensityY = 300;
             *        JpegEncoder encoder = new JpegEncoder();
             *        encoder.Encode(Img, mstream3);
             *        MemoryStream mss3 = new MemoryStream(mstream3.ToArray());
             *        mss3.Seek(0, SeekOrigin.Begin);
             *        XImage pdfImg3 = XImage.FromStream(mss3);
             *        pdfImg3.Interpolate = false;
             *        gfx3.DrawImage(pdfImg3, 0, 0, 797, 1123);
             *
             *    }
             * }
             * }*/
        }
示例#7
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);
        }
示例#8
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;
        }
示例#9
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;
                    }
                }
            }
        }
示例#10
0
 private void ShowVerifyCodeInput(string imgUrl)
 {
     Dispatcher.BeginInvoke(() =>
     {
         VerifyCodeStack.Visibility = Visibility.Visible;
         ImageTools.IO.Decoders.AddDecoder<GifDecoder>();
         ImageTools.IO.Decoders.AddDecoder<BmpDecoder>();
         ImageTools.IO.Decoders.AddDecoder<JpegDecoder>();
         ImageTools.IO.Decoders.AddDecoder<PngDecoder>();
         ImageTools.ExtendedImage img = new ImageTools.ExtendedImage();
         img.UriSource = new Uri(imgUrl, UriKind.RelativeOrAbsolute);
         VerifyCodeImage.Source = img;
     });
 }
示例#11
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;
					}
				}
			}
		}