Example #1
0
        private async Task <List <BitmapImage> > Test2()
        {
            var streams = new List <Windows.Storage.Streams.InMemoryRandomAccessStream>();
            var images  = new List <BitmapImage>();

            for (uint i = 0; i < MyPdfDocument.PageCount; i++)
            {
                using (var neko = MyPdfDocument.GetPage(i))
                {
                    using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                    {
                        await neko.RenderToStreamAsync(stream);

                        streams.Add(stream);
                        var img = new BitmapImage();
                        img.BeginInit();
                        img.CacheOption  = BitmapCacheOption.OnLoad;
                        img.StreamSource = stream.AsStream();
                        img.EndInit();
                        images.Add(img);
                    }
                }
            }
            return(images);
        }
Example #2
0
        /// <summary>
        /// jpeg画像で保存
        /// </summary>
        /// <param name="dpi">PDFファイルを読み込む時のDPI</param>
        /// <param name="directory">保存フォルダ</param>
        /// <param name="fileName">保存名</param>
        /// <param name="pageIndex">保存するPDFのページ</param>
        /// <param name="quality">jpegの品質min0、max100</param>
        /// <param name="keta">保存名につける連番0埋めの桁数</param>
        /// <returns></returns>
        private async Task SaveSub2(double dpi, string directory, string fileName, int pageIndex, int quality, int keta)
        {
            using (Windows.Data.Pdf.PdfPage page = MyPdfDocument.GetPage((uint)pageIndex))
            {
                //指定されたdpiを元に画像サイズ指定、四捨五入
                var options = new Windows.Data.Pdf.PdfPageRenderOptions();
                options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero);

                using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    await page.RenderToStreamAsync(stream, options);

                    BitmapImage image = new BitmapImage();
                    image.BeginInit();
                    image.CacheOption  = BitmapCacheOption.OnLoad;
                    image.StreamSource = stream.AsStream();
                    image.EndInit();

                    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                    encoder.QualityLevel = quality;
                    encoder.Frames.Add(BitmapFrame.Create(image));
                    pageIndex++;
                    string renban = pageIndex.ToString("d" + keta);
                    using (var fileStream = new FileStream(
                               System.IO.Path.Combine(directory, fileName) + "_" + renban + ".jpg", FileMode.Create, FileAccess.Write))
                    {
                        encoder.Save(fileStream);
                    }
                }
            }
        }
Example #3
0
        private async void ButtonOpenScale_Click(object sender, RoutedEventArgs e)
        {
            var file = await Windows.Storage.StorageFile.GetFileFromPathAsync(@"D:\ブログ用\1708_04.pdf");
            try
            {
                PdfDocument = await Windows.Data.Pdf.PdfDocument.LoadFromFileAsync(file);
            }
            catch (Exception)
            {

            }

            if (PdfDocument != null)
            {
                using (Windows.Data.Pdf.PdfPage page = PdfDocument.GetPage(0))
                {
                    BitmapImage image = new BitmapImage();
                    using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                    {
                        var options = new Windows.Data.Pdf.PdfPageRenderOptions();
                        options.DestinationHeight = 1000;
                        await page.RenderToStreamAsync(stream, options);

                        image.BeginInit();
                        image.CacheOption = BitmapCacheOption.OnLoad;
                        image.StreamSource = stream.AsStream();
                        image.EndInit();
                    }
                    ImagePDF.Source = image;
                }
            }
        }
Example #4
0
        private async void DisplayImage(int pageIndex, double dpi)
        {
            if (MyPdfDocument == null)
            {
                return;
            }
            MyDpi = dpi;
            using (Windows.Data.Pdf.PdfPage page = MyPdfDocument.GetPage((uint)pageIndex))
            {
                double h       = page.Size.Height;
                var    options = new Windows.Data.Pdf.PdfPageRenderOptions();
                options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero);
                tbDpi.Text    = $"dpi : {dpi.ToString()}";
                tbHeight.Text = $"縦ピクセル : {options.DestinationHeight.ToString()}";

                using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    await page.RenderToStreamAsync(stream, options);

                    BitmapImage image = new BitmapImage();
                    image.BeginInit();
                    image.CacheOption  = BitmapCacheOption.OnLoad;
                    image.StreamSource = stream.AsStream();//using System.IOがないとエラーになる
                    image.EndInit();
                    MyImage.Source = image;
                    MyImage.Width  = image.PixelWidth;
                    MyImage.Height = image.PixelHeight;
                }
            }
        }
Example #5
0
        private async Task <int> SaveSubTask(double rate, string filePath, uint i)
        {
            using (Windows.Data.Pdf.PdfPage page = PdfDocument.GetPage((uint)i))
            {
                //指定されたdpiを元にレンダーサイズ指定、四捨五入
                double h       = page.Size.Height;
                var    options = new Windows.Data.Pdf.PdfPageRenderOptions();
                options.DestinationHeight = (uint)Math.Round(h * rate, MidpointRounding.AwayFromZero);

                using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    await page.RenderToStreamAsync(stream, options);

                    BitmapImage image = new BitmapImage();
                    image.BeginInit();
                    image.CacheOption  = BitmapCacheOption.OnLoad;
                    image.StreamSource = stream.AsStream();
                    image.EndInit();

                    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                    encoder.QualityLevel = 85;
                    encoder.Frames.Add(BitmapFrame.Create(image));
                    using (var fileStream = new FileStream(filePath + "_" + i + ".jpg", FileMode.Create, FileAccess.Write))
                    {
                        encoder.Save(fileStream);
                    }
                }
            }
            return((int)i);
        }
Example #6
0
        /// <summary>
        /// jpeg画像で保存
        /// </summary>
        private async Task SaveSub2_1(int pageIndex, int keta, bool isJpeg)
        {
            var encoder = MakeEncoder(isJpeg);

            using (PdfPage page = MyPdfDocument.GetPage((uint)pageIndex))
            {
                string ext = isJpeg ? ".jpg" : ".png";
                //指定されたdpiを元に画像サイズ指定、四捨五入
                var options = new PdfPageRenderOptions();
                options.DestinationHeight = (uint)Math.Round(page.Size.Height * (MyDpi / 96.0), MidpointRounding.AwayFromZero);

                using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    await page.RenderToStreamAsync(stream, options);//画像に変換したのはstreamへ

                    //streamから直接BitmapFrameを作成することができた
                    encoder.Frames.Add(BitmapFrame.Create(stream.AsStream()));
                    //連番ファイル名を作成して保存
                    pageIndex++;
                    string renban = pageIndex.ToString("d" + keta);

                    using (var fileStream = new FileStream(
                               System.IO.Path.Combine(MyPdfDirectory, MyPdfName) + "_" + renban + ext, FileMode.Create, FileAccess.Write))
                    {
                        encoder.Save(fileStream);
                    }
                }
            }
        }
Example #7
0
        public static async Task <string> GetFullTextFromImage(Image img)
        {
            try
            {
                StringBuilder b = new StringBuilder();

                using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    img.Save(stream.AsStream(), System.Drawing.Imaging.ImageFormat.Bmp);
                    //These steps to get to a SoftwareBitmap are aweful!
                    Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);

                    SoftwareBitmap bitmap = await decoder.GetSoftwareBitmapAsync();

                    OcrResult ocrResult = await _ocrEngine.RecognizeAsync(bitmap);

                    for (int i = 0; i < ocrResult.Lines.Count; i++)
                    {
                        b.Append(ocrResult.Lines[i].Text);
                        b.Append(" ");
                    }
                }
                return(b.ToString());
            }catch (Exception ex)
            {
                Logger.Error(ex.ToString());
            }
            return(string.Empty);
        }
Example #8
0
        public static async Task <string> GetFullText2(string pathToImg)
        {
            Bitmap bmp    = new Bitmap(pathToImg);
            int    width  = bmp.Width;
            int    height = bmp.Height;


            using (Graphics g = Graphics.FromImage(bmp))
            {
                // copy rectangle from screen (doesn't include cursor)

                using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    //These steps to get to a SoftwareBitmap are aweful!
                    bmp.Save(stream.AsStream(), System.Drawing.Imaging.ImageFormat.Bmp);//choose the specific image format by your own bitmap source
                    Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);

                    SoftwareBitmap bitmap = await decoder.GetSoftwareBitmapAsync();

                    OcrResult ocrResult = await _ocrEngine.RecognizeAsync(bitmap);

                    for (int i = 0; i < ocrResult.Lines.Count; i++)
                    {
                        OcrLine line = ocrResult.Lines[i];
                    }
                }
            }
            return(string.Empty);
        }
Example #9
0
        //ロックじゃない開き方
        private async void ButtonFree_Click(object sender, RoutedEventArgs e)
        {
            Windows.Storage.StorageFile file = await Windows.Storage.StorageFile.GetFileFromPathAsync(@"D:\ブログ用\1708_04.pdf");

            //ここから
            using (Windows.Storage.Streams.IRandomAccessStream RAStream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read))
            {
                Windows.Data.Pdf.PdfDocument MyPdfDocument = await Windows.Data.Pdf.PdfDocument.LoadFromStreamAsync(RAStream);

                //ここまで
                using (Windows.Data.Pdf.PdfPage page = MyPdfDocument.GetPage(0))
                {
                    using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                    {
                        await page.RenderToStreamAsync(stream);

                        var image = new BitmapImage();
                        image.BeginInit();
                        image.CacheOption  = BitmapCacheOption.OnLoad;
                        image.StreamSource = stream.AsStream();
                        image.EndInit();
                        MyImage.Source = image;
                    }
                }
            }
        }
Example #10
0
        /// <summary>
        /// 表示
        /// </summary>
        /// <param name="pageNumber">指定ページ</param>
        /// <param name="displayDpi">指定dpi、通常なら96</param>
        private async void PageLoad(uint pageNumber, double displayDpi)
        {
            if (PdfDocument == null)
            {
                return;
            }
            BitmapImage image = new BitmapImage();
            var         rate  = displayDpi / 96.0;//表示倍率みたいなもの

            using (Windows.Data.Pdf.PdfPage page = PdfDocument.GetPage(pageNumber))
            {
                //指定されたdpiを元にレンダーサイズ指定、四捨五入
                double h       = page.Size.Height;
                var    options = new Windows.Data.Pdf.PdfPageRenderOptions();
                options.DestinationHeight = (uint)Math.Round(h * rate, MidpointRounding.AwayFromZero);

                using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    await page.RenderToStreamAsync(stream, options);

                    image.BeginInit();
                    image.CacheOption  = BitmapCacheOption.OnLoad;
                    image.StreamSource = stream.AsStream();
                    image.EndInit();
                }
            }
            MyImage.Source = image;
            MyImage.Width  = image.PixelWidth;
            MyImage.Height = image.PixelHeight;
        }
Example #11
0
        private async Task Save5(PdfDocument pdfDocument, ZipArchive archive, int keta, int quality, double dpi)
        {
            for (int i = 0; i < MyPdfDocument.PageCount; i++)
            {
                int    renban   = i + 1;
                string jpegName = MyPdfName + "_" + renban.ToString("d" + keta) + ".jpg";

                using (PdfPage page = pdfDocument.GetPage((uint)i))
                {
                    var options = new PdfPageRenderOptions();
                    options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero);

                    using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                    {
                        await page.RenderToStreamAsync(stream, options);//画像に変換したのはstreamへ

                        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                        encoder.QualityLevel = quality;
                        encoder.Frames.Add(BitmapFrame.Create(stream.AsStream()));

                        var entry = archive.CreateEntry(jpegName);
                        //open
                        using (var entryStream = entry.Open())
                        {
                            using (var jpegStream = new MemoryStream())
                            {
                                encoder.Save(jpegStream);
                                jpegStream.Position = 0;
                                jpegStream.CopyTo(entryStream);
                            }
                        }
                    }
                }
            }
        }
Example #12
0
        public async Task <Stream> GetBitmapAsync()
        {
            var softwareBitmap = await capture.GetCaptureAsync();

            var stream  = new Windows.Storage.Streams.InMemoryRandomAccessStream();
            var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, stream);

            encoder.SetSoftwareBitmap(softwareBitmap);
            await encoder.FlushAsync();

            return(stream.AsStream());
        }
Example #13
0
        /// <summary>
        /// PdfDocumentをjpegにして、1つのzipファイルにする
        /// </summary>
        /// <param name="pdfDocument">Windows.Data.Pdf</param>
        /// <param name="dpi">PDFを画像にするときに使う</param>
        /// <param name="directory">保存フォルダ</param>
        /// <param name="fileName">zipファイル名とjpegファイル名に使う</param>
        /// <param name="quality">jpeg品質</param>
        /// <param name="keta">0埋め連番の桁数、jpegファイル名に使う</param>
        /// <returns></returns>
        private async Task SaveSub3_1(PdfDocument pdfDocument, double dpi, string directory, string fileName, int quality, int keta, bool isJpeg)
        {
            string        exte = isJpeg ? ".jpg" : ".png";
            BitmapEncoder encoder;
            string        zipName = System.IO.Path.Combine(directory, fileName) + ".zip";

            using (var zipstream = File.Create(zipName))
            {
                using (ZipArchive archive = new ZipArchive(zipstream, ZipArchiveMode.Create))
                {
                    for (int i = 0; i < MyPdfDocument.PageCount; i++)
                    {
                        int    renban   = i + 1;
                        string jpegName = MyPdfName + "_" + renban.ToString("d" + keta) + exte;
                        if (isJpeg)
                        {
                            JpegBitmapEncoder j = new JpegBitmapEncoder();
                            j.QualityLevel = quality;
                            encoder        = j;
                        }
                        else
                        {
                            encoder = new PngBitmapEncoder();
                        }

                        using (PdfPage page = pdfDocument.GetPage((uint)i))
                        {
                            var options = new PdfPageRenderOptions();
                            options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero);

                            using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                            {
                                await page.RenderToStreamAsync(stream, options);//画像に変換したのはstreamへ

                                encoder.Frames.Add(BitmapFrame.Create(stream.AsStream()));
                                var entry = archive.CreateEntry(jpegName);
                                //open
                                using (var entryStream = entry.Open())
                                {
                                    using (var jpegStream = new MemoryStream())
                                    {
                                        encoder.Save(jpegStream);
                                        jpegStream.Position = 0;
                                        jpegStream.CopyTo(entryStream);
                                    }
                                }
                            }
                        }
                    }//for
                }
            }
        }
        async Task <OcrResult> RecognizeBitmapAsync(Bitmap b)
        {
            // Need to marshall from Drawing.Bitmap to UWP SoftwareBitmap
            using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
            {
                b.Save(stream.AsStream(), System.Drawing.Imaging.ImageFormat.Bmp);                //choose the specific image format by your own bitmap source
                Windows.Graphics.Imaging.BitmapDecoder decoder = await Windows.Graphics.Imaging.BitmapDecoder.CreateAsync(stream);

                Windows.Graphics.Imaging.SoftwareBitmap softwareBitmap = await decoder.GetSoftwareBitmapAsync();

                return(await engine.RecognizeAsync(softwareBitmap));
            }
        }
Example #15
0
        //全ページBitmapSourceのリスト
        private async void ButtonTest2_Click(object sender, RoutedEventArgs e)
        {
            List <BitmapFrame> frames = new List <BitmapFrame>();
            var ps = GetPages();

            for (int i = 0; i < ps.Count; i++)
            {
                using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    await ps[i].RenderToStreamAsync(stream);
                    frames.Add(BitmapFrame.Create(stream.AsStream()));
                }
            }
        }
Example #16
0
        private async Task <BitmapImage> MakeImage(Windows.Data.Pdf.PdfPage page)
        {
            var img = new BitmapImage();

            using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
            {
                await page.RenderToStreamAsync(stream);

                img.BeginInit();
                img.CacheOption  = BitmapCacheOption.OnLoad;
                img.StreamSource = stream.AsStream();
                img.EndInit();
            }
            return(img);
        }
Example #17
0
        //PDFファイルを画像に変換して表示
        private async void DisplayImage(int pageIndex, double dpi)
        {
            if (MyPdfDocument == null)
            {
                return;
            }

            int c = (int)MyPdfDocument.PageCount - 1;

            if (pageIndex > c)
            {
                pageIndex = c;
            }
            if (pageIndex < 0)
            {
                pageIndex = 0;
            }

            MyDpi = dpi;
            using (PdfPage page = MyPdfDocument.GetPage((uint)pageIndex))
            {
                //作成する画像の縦ピクセル数を指定されたdpiから決める
                var options = new PdfPageRenderOptions();
                options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero);
                options.DestinationWidth  = (uint)Math.Round(page.Size.Width * (dpi / 96.0), MidpointRounding.AwayFromZero);
                tbDpi.Text    = $"{dpi.ToString()} dpi";
                tbHeight.Text = $"縦{options.DestinationHeight.ToString()} px";
                tbWidth.Text  = $"横{options.DestinationWidth.ToString()} px";

                //画像に変換
                using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    await page.RenderToStreamAsync(stream, options);//画像に変換はstreamへ

                    BitmapImage image = new BitmapImage();
                    image.BeginInit();
                    image.CacheOption  = BitmapCacheOption.OnLoad;
                    image.StreamSource = stream.AsStream();//using System.IOがないとエラーになる
                    image.EndInit();
                    MyImage.Source = image;
                    MyImage.Width  = image.PixelWidth;
                    MyImage.Height = image.PixelHeight;
                    //プレビュー用のjpeg画像表示
                    MyImagePreviwer.Source = MakeJpegPreviewImage(image, GetJpegQualityFix());
                    UpdateDisplayPngSize(image);//pngサイズ表示更新
                }
            }
        }
Example #18
0
        //未検証、ページから画像作成から保存までの処理をTaskにする、あとでTaskWhenAllで実行?
        private async Task SaveTaskAsync(Windows.Data.Pdf.PdfPage page, string directory, string fileName, int pageIndex, int quality, int keta)
        {
            using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
            {
                await page.RenderToStreamAsync(stream);

                var encoder = new JpegBitmapEncoder();
                encoder.QualityLevel = quality;
                encoder.Frames.Add(BitmapFrame.Create(stream.AsStream()));
                string renban = pageIndex.ToString("d" + keta);
                using (var fileStream = new FileStream(
                           System.IO.Path.Combine(directory, fileName) + "_" + renban + ".jpg", FileMode.Create, FileAccess.Write))
                {
                    encoder.Save(fileStream);
                }
            }
        }
Example #19
0
        private void ShowImageAsync(Windows.Storage.Streams.InMemoryRandomAccessStream bitmapStream)
        {
            //var bitmap = new Windows.UI.Xaml.Media.Imaging.BitmapImage();
            //await bitmap.SetSourceAsync(bitmapStream);

            //image1.Width = bitmap.PixelWidth;
            //image1.Height = bitmap.PixelHeight;
            //image1.Source = bitmap;

            var bitmap = new BitmapImage();

            bitmap.BeginInit();
            bitmap.CacheOption  = BitmapCacheOption.OnLoad;
            bitmap.StreamSource = bitmapStream.AsStream();
            bitmap.EndInit();
            image1.Source = bitmap;
        }
Example #20
0
        public async static Task <BitmapImage> BitmapImageFromPdf(Byte[] bytes)
        {
            Windows.Data.Pdf.PdfDocument pdfDocument;

            using (var stream = new MemoryStream(bytes))
            {
                pdfDocument = await Windows.Data.Pdf.PdfDocument.LoadFromStreamAsync(stream.AsRandomAccessStream());

                if (pdfDocument != null)
                {
                    // 1ページ目を読み込む
                    using (Windows.Data.Pdf.PdfPage page = pdfDocument.GetPage(0))
                    {
                        BitmapImage image = new BitmapImage();

                        using (var IMRAStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                        {
                            await page.RenderToStreamAsync(IMRAStream);

                            image.BeginInit();
                            image.CacheOption  = BitmapCacheOption.OnLoad;
                            image.StreamSource = IMRAStream.AsStream();
                            image.EndInit();
                        }

                        /*
                         * // save to file.
                         * JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                         * encoder.Frames.Add(BitmapFrame.Create(image));
                         *
                         * //string filePath = @"C:\Users\hoge\Desktop\test.jpg";
                         * using (var fileStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create, FileAccess.Write))
                         * {
                         *  encoder.Save(fileStream);
                         * }
                         */
                        return(image);
                    }
                }
            }

            return(null);
        }
Example #21
0
        protected List <Stream> ConvertPdfToStream(Stream stream)
        {
            var loadFromStreamAsyncTask = PdfDocument.LoadFromStreamAsync(stream.AsRandomAccessStream()).AsTask();

            loadFromStreamAsyncTask.Wait();
            var pdfDocument = loadFromStreamAsyncTask.Result;

            List <string> result = new List <string>();

            return(Enumerable.Range(0, (int)pdfDocument.PageCount).Select((index) =>
            {
                using (PdfPage page = pdfDocument.GetPage((uint)index))
                    using (var convertStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                    {
                        var renderToStreamAsyncTask = page.RenderToStreamAsync(convertStream).AsTask();
                        renderToStreamAsyncTask.Wait();

                        return convertStream.AsStream();
                    }
            }).ToList());
        }
Example #22
0
        private async void MakeImageAndSave(double displayDpi)
        {
            if (PdfDocument == null)
            {
                return;
            }
            string filePath = @"D:\ブログ用\1708_04";

            var rate = displayDpi / 96.0;//表示倍率みたいなもの

            for (uint i = 0; i < PdfDocument.PageCount; i++)
            {
                using (Windows.Data.Pdf.PdfPage page = PdfDocument.GetPage(i))
                {
                    //指定されたdpiを元にレンダーサイズ指定、四捨五入
                    double h       = page.Size.Height;
                    var    options = new Windows.Data.Pdf.PdfPageRenderOptions();
                    options.DestinationHeight = (uint)Math.Round(h * rate, MidpointRounding.AwayFromZero);

                    using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                    {
                        await page.RenderToStreamAsync(stream, options);

                        BitmapImage image = new BitmapImage();
                        image.BeginInit();
                        image.CacheOption  = BitmapCacheOption.OnLoad;
                        image.StreamSource = stream.AsStream();
                        image.EndInit();

                        JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                        encoder.QualityLevel = 85;
                        encoder.Frames.Add(BitmapFrame.Create(image));
                        using (var fileStream = new FileStream(filePath + "_" + i + ".jpg", FileMode.Create, FileAccess.Write))
                        {
                            encoder.Save(fileStream);
                        }
                    }
                }
            }
        }
Example #23
0
        private BitmapImage RenderPage(double dpi, int pageIndex)
        {
            BitmapImage image = new BitmapImage();

            using (Windows.Data.Pdf.PdfPage page = MyPdfDocument.GetPage((uint)pageIndex))
            {
                //指定されたdpiを元に画像サイズ指定、四捨五入
                var options = new Windows.Data.Pdf.PdfPageRenderOptions();
                options.DestinationHeight = (uint)Math.Round(page.Size.Height * (dpi / 96.0), MidpointRounding.AwayFromZero);

                using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                {
                    page.RenderToStreamAsync(stream, options);

                    image.BeginInit();
                    image.CacheOption  = BitmapCacheOption.OnLoad;
                    image.StreamSource = stream.AsStream();
                    image.EndInit();
                }
            }
            return(image);
        }
Example #24
0
        public ImageForm(IVisualizerObjectProvider objectProvider)
        {
            InitializeComponent();

#if DEBUG
            ShowInTaskbar = true;
#endif

            label1.Font = UIFont;
            SetFontAndScale(label1, UIFont);
            label2.Font        = UIFont;
            txtExpression.Font = UIFont;
            CloseB.Font        = UIFont;

            object objectBitmap = objectProvider.GetObject();

            object image = null;

            if (objectBitmap != null)
            {
                if (objectBitmap is ByteArraySerializableWrapper <SoftwareBitmap> wrapper)
                {
                    image = Serializer.ToSoftwareBitmap(wrapper.Bytes);
                }
#if DEBUG
                string expression = objectBitmap.ToString();
#endif

                var method = objectBitmap.GetType().GetMethod("ToBitmap", new Type[] { });
                if (method != null)
                {
                    objectBitmap = method.Invoke(objectBitmap, null);
                }

                System.Windows.Media.ImageSource bitmapSource = null;

                if (objectBitmap is Bitmap)
                {
                    image = objectBitmap;
                    //var hObject = ((Bitmap)objectBitmap).GetHbitmap();

                    //try
                    //{
                    //    bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    //           hObject,
                    //           IntPtr.Zero,
                    //           Int32Rect.Empty,
                    //           BitmapSizeOptions.FromEmptyOptions());
                    //    image = bitmapSource;
                    //}
                    //catch (Win32Exception)
                    //{
                    //    bitmapSource = null;
                    //}
                    //finally
                    //{
                    //    DeleteObject(hObject);
                    //}
                }
                else
                if (objectBitmap is SerializableBitmapImage serializableBitmapImage)
                {
                    if (serializableBitmapImage.Image != null)
                    {
                        bitmapSource = (System.Windows.Media.Imaging.BitmapSource)serializableBitmapImage;
                    }
                    else if (serializableBitmapImage.SoftwareBitmap != null)
                    {
                        using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
                        {
                            Windows.Graphics.Imaging.BitmapEncoder encoder = Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, stream).GetResults();
                            encoder.SetSoftwareBitmap(serializableBitmapImage.SoftwareBitmap);
                            var t = Task.Run(async() => await encoder.FlushAsync());
                            t.GetAwaiter().GetResult();

                            var bitmap = new BitmapImage();
                            bitmap.BeginInit();
                            bitmap.StreamSource = stream.AsStream();
                            bitmap.CacheOption  = BitmapCacheOption.OnLoad;
                            bitmap.EndInit();
                            bitmap.Freeze();
                            bitmapSource = bitmap;
                            image        = (ImageSource)bitmap;
                            // use bitmap
                        }
                        //using (var sb = serializableBitmapImage.SoftwareBitmap.LockBuffer())
                        //{

                        //    var source = WriteableBitmap.Create(serializableBitmapImage.SoftwareBitmap.PixelWidth, serializableBitmapImage.SoftwareBitmap.PixelHeight, serializableBitmapImage.SoftwareBitmap.DpiX, serializableBitmapImage.SoftwareBitmap.DpiY,
                        //        serializableBitmapImage.SoftwareBitmap.BitmapPixelFormat, null, sb.CreateReference()., serializableBitmapImage.SoftwareBitmap.PixelWidth);
                        //    source.

                        //}
                        //    var bs = new SoftwareBitmapSource();
                        //    await bs.SetBitmapAsync(serializableBitmapImage.SoftwareBitmap);
                        //bitmapSource = bs;
                    }
                }

                //if (bitmapSource != null)
                //{
                //    imageControl.SetImage(bitmapSource);
                //}

                var type = image.GetType();
                Func <ImageUserControl> factory = null;
                while (type != null && !ImageControls.TryGetValue(type, out factory))
                {
                    type = type.BaseType;
                }
                if (factory is { })