예제 #1
0
        public void ToColorBitmapQ(int h, int w, int b, ColorImageFormat f, byte[] pd)
        {
            int width  = w;
            int height = h;
            int bpp    = b;
            var format = f;

            byte[] pixelData = pd;
            int    stride    = width * PixelFormats.Bgr32.BitsPerPixel / 8;
            var    temp      = BitmapSource.Create(width, height, 96.0, 96.0, PixelFormats.Bgr32, null, pixelData, stride);

            temp.Freeze();
            long             milliseconds = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond;
            MemoryStream     mems         = new MemoryStream();
            WmpBitmapEncoder encoder      = new WmpBitmapEncoder();
            BitmapFrame      bframe       = BitmapFrame.Create(temp);

            encoder.ImageQualityLevel = qual;
            encoder.Frames.Add(bframe);
            encoder.Save(mems);
            qual -= 0.0001F;
            qual  = Math.Max(qual, 0);
            try
            {
                MainWindow.RGBConcurrentQueue.Enqueue(mems);
            }
            catch (Exception e)
            {
                qual = 0;
            }
        }
예제 #2
0
        /// <summary>
        /// Write the bitmap to the file in the encoding implied by the extension of the
        /// destination file.
        /// </summary>
        /// <param name="Bitmap"></param>
        /// <param name="ToFilePath"></param>
        public static void WriteToFile(this BitmapSource Bitmap, string ToFilePath)
        {
            var ext = global::System.IO.Path.GetExtension(ToFilePath).ToLower();
            var ms  = new MemoryStream();

            if ((ext == ".jpg") || (ext == ".jpeg"))
            {
                var encoder = new JpegBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Bitmap));
                encoder.Save(ms);
            }

            else if ((ext == ".tif") || (ext == ".tiff"))
            {
                var encoder = new TiffBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Bitmap));
                encoder.Save(ms);
            }

            else if (ext == ".png")
            {
                var encoder = new PngBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Bitmap));
                encoder.Save(ms);
            }

            else if (ext == ".bmp")
            {
                var encoder = new BmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Bitmap));
                encoder.Save(ms);
            }

            else if (ext == ".gif")
            {
                var encoder = new GifBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Bitmap));
                encoder.Save(ms);
            }

            else if (ext == ".wmp")
            {
                var encoder = new WmpBitmapEncoder();
                encoder.Frames.Add(BitmapFrame.Create(Bitmap));
                encoder.Save(ms);
            }

            else
            {
                throw new Exception("extension of file " + ToFilePath + " not supported.");
            }

            byte[] bytes = new byte[ms.Length];
            ms.Seek(0, SeekOrigin.Begin);
            ms.Read(bytes, 0, (int)ms.Length);
            ms.Close();

            global::System.IO.File.WriteAllBytes(ToFilePath, bytes);
        }
        /// <summary>
        ///     Gets the encoded image data.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="preferredFormat">The preferred Image format.</param>
        /// <param name="qualityLevel">JpegBitmapEncoder QualityLevel</param>
        /// <returns></returns>
        public static byte[] ToEncodedBuffer(this BitmapSource image, ImageFormat preferredFormat, int qualityLevel)
        {
            byte[]        result  = default(byte[]);
            BitmapEncoder encoder = default(BitmapEncoder);

            if (image == null)
            {
                return(null);
            }

            switch (preferredFormat)
            {
            case ImageFormat.JPEG:
            case ImageFormat.JPG:
                encoder = new JpegBitmapEncoder
                {
                    QualityLevel = qualityLevel
                };
                break;

            case ImageFormat.BMP:
                encoder = new BmpBitmapEncoder();
                break;

            case ImageFormat.PNG:
                encoder = new PngBitmapEncoder();
                break;

            case ImageFormat.TIFF:
            case ImageFormat.TIF:
                encoder = new TiffBitmapEncoder();
                break;

            case ImageFormat.GIF:
                encoder = new GifBitmapEncoder();
                break;

            case ImageFormat.WMP:
                encoder = new WmpBitmapEncoder();
                break;
            }
            using (var stream = new MemoryStream())
            {
                if (encoder != null)
                {
                    encoder.Frames.Add(BitmapFrame.Create(image));
                    encoder.Save(stream);
                }
                stream.Seek(0, SeekOrigin.Begin);
                result = new byte[stream.Length];
                using (var br = new BinaryReader(stream))
                {
                    br.Read(result, 0, (int)stream.Length);
                    br.Close();
                }
                stream.Close();
                return(result);
            }
        }
예제 #4
0
        public void CaptureSnapshot()
        {
            RenderTargetBitmap renderTarget = Window.CaptureSnapshot();

            Microsoft.Win32.SaveFileDialog saveFileDialog = new Microsoft.Win32.SaveFileDialog();
            saveFileDialog.Filter       = "BMP files (*.bmp)|*.bmp|GIF files (*.gif)|*.gif|JPEG files (*.jpg)|*.jpg|PNG files (*.png)|*.png|TIFF files (*.tif)|*.tif|WMP files (*.wmp)|*.wmp|All files (*.*)|*.*";
            saveFileDialog.FilterIndex  = 4;
            saveFileDialog.DefaultExt   = "png";
            saveFileDialog.FileName     = DateTime.Now.ToString("yyyyMMddHHmmssffff");
            saveFileDialog.AddExtension = true;
            if (saveFileDialog.ShowDialog(Window) == false)
            {
                return;
            }

            BitmapFrame   bitmapFrame   = BitmapFrame.Create(renderTarget);
            BitmapEncoder bitmapEncoder = null;

            switch (Path.GetExtension(saveFileDialog.FileName).Substring(1).ToLower())
            {
            case "bmp":
                bitmapEncoder = new BmpBitmapEncoder();
                break;

            case "gif":
                bitmapEncoder = new GifBitmapEncoder();
                break;

            case "jpg":
            case "jpeg":
                bitmapEncoder = new JpegBitmapEncoder();
                break;

            case "png":
                bitmapEncoder = new PngBitmapEncoder();
                break;

            case "tif":
            case "tiff":
                bitmapEncoder = new TiffBitmapEncoder();
                break;

            case "wmp":
                bitmapEncoder = new WmpBitmapEncoder();
                break;
            }
            if (bitmapEncoder == null)
            {
                MessageBox.Show("不支持的格式");
                return;
            }
            bitmapEncoder.Frames.Add(bitmapFrame);
            using (FileStream fileStream = new FileStream("capture.png", FileMode.Create, FileAccess.Write))
            {
                bitmapEncoder.Save(fileStream);
            }
        }
예제 #5
0
 /// <summary>
 /// Сохранить изображение в формате WMP (Microsoft Windows Media Photo).
 /// </summary>
 /// <param name="bmp">Сохраняемое изображение</param>
 /// <param name="path">Путь по которому будет сохранено изображение</param>
 public static void SaveInWmp(BitmapSource bmp, string path)
 {
     using (FileStream fileStream = new FileStream(path, FileMode.CreateNew, FileAccess.Write, FileShare.None))
     {
         WmpBitmapEncoder wmpEncoder = new WmpBitmapEncoder();
         wmpEncoder.Frames.Add(BitmapFrame.Create(bmp));
         wmpEncoder.Save(fileStream);
     }
 }
예제 #6
0
        /// <summary>
        /// Save a solved map to an image file.
        /// </summary>
        /// <param name="path"></param>
        /// <param name="map"></param>
        /// <param name="outputPath"></param>
        public static void OutputBitmap(
            MapPath path,
            Map map,
            string outputPath)
        {
            // Get pixels from original map data.
            byte[] pixels = path.TraceOverMap(map);

            // Output the bitmap.
            string        extension = Path.GetExtension(outputPath);
            BitmapEncoder encoder;

            switch (extension)
            {
            default:
                encoder = new BmpBitmapEncoder();
                break;

            case ".png":
                encoder = new PngBitmapEncoder();
                break;

            case ".gif":
                encoder = new GifBitmapEncoder();
                break;

            case ".tif":
            case "tiff":
                encoder = new TiffBitmapEncoder();
                break;

            case ".jpg":
            case "jpeg":
                encoder = new JpegBitmapEncoder();
                break;

            case ".wmp":
                encoder = new WmpBitmapEncoder();
                break;
            }

            Console.WriteLine(extension);

            // TODO: Figure out why files have no compression.
            int          stride       = map.Width * Map.BytesPerPixel;
            BitmapSource bitmapSource = BitmapSource.Create(
                map.Width, map.Height,
                96, 96,
                PixelFormats.Bgra32, null, pixels, stride);

            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));

            using (FileStream filestream = new FileStream(outputPath, FileMode.Create))
            {
                encoder.Save(filestream);
            }
        }
예제 #7
0
        internal byte[] GetEncodedImageData(ImageSource image, string preferredFormat)
        {
            try
            {
                byte[]        result  = null;
                BitmapEncoder encoder = null;
                switch (preferredFormat.ToLower())
                {
                case ".jpg":
                case ".jpeg":
                    encoder = new JpegBitmapEncoder();
                    break;

                case ".bmp":
                    encoder = new BmpBitmapEncoder();
                    break;

                case ".png":
                    encoder = new PngBitmapEncoder();
                    break;

                case ".tif":
                case ".tiff":
                    encoder = new TiffBitmapEncoder();
                    break;

                case ".gif":
                    encoder = new GifBitmapEncoder();
                    break;

                case ".wmp":
                    encoder = new WmpBitmapEncoder();
                    break;
                }
                if (image is BitmapSource)
                {
                    MemoryStream stream = new MemoryStream();
                    encoder.Frames.Add(BitmapFrame.Create(image as BitmapSource));
                    encoder.Save(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    result = new byte[stream.Length];
                    BinaryReader br = new BinaryReader(stream);
                    br.Read(result, 0, (int)stream.Length);
                    br.Close();
                    stream.Close();
                }
                return(result);
            }
            catch (System.Exception ex1)
            {
                MessageBox.Show("exception: " + ex1, "Error!");
            }
            return(null);
        }
예제 #8
0
        private static byte[] GetEncodedImageData(BitmapSource source, string preferredFormat)
        {
            byte[]        result = null;
            BitmapEncoder encoder;

            switch (preferredFormat.ToLower())
            {
            case ".jpg":
            case ".jpeg":
                encoder = new JpegBitmapEncoder();
                break;

            case ".bmp":
                encoder = new BmpBitmapEncoder();
                break;

            case ".png":
                encoder = new PngBitmapEncoder();
                break;

            case ".tif":
            case ".tiff":
                encoder = new TiffBitmapEncoder();
                break;

            case ".gif":
                encoder = new GifBitmapEncoder();
                break;

            case ".wmp":
                encoder = new WmpBitmapEncoder();
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            encoder.Frames.Add(BitmapFrame.Create(source));

            using (var stream = new MemoryStream())
            {
                encoder.Save(stream);
                stream.Seek(0, SeekOrigin.Begin);
                result = new byte[stream.Length];
                using (var br = new BinaryReader(stream))
                {
                    br.Read(result, 0, (int)stream.Length);
                }
            }

            return(result);
        }
예제 #9
0
        internal byte[] GetEncodedImageData(ImageSource image, string preferredFormat)

        {
            byte[] result = null;

            BitmapEncoder encoder = null;

            switch (preferredFormat.ToLower())

            {
            case ".jpg":
            case ".jpeg":
                encoder = new JpegBitmapEncoder();
                break;

            case ".bmp":
                encoder = new BmpBitmapEncoder();
                break;

            case ".png":
                encoder = new PngBitmapEncoder();
                break;

            case ".tif":
            case ".tiff":
                encoder = new TiffBitmapEncoder();
                break;

            case ".gif":
                encoder = new GifBitmapEncoder();
                break;

            case ".wmp":
                encoder = new WmpBitmapEncoder();
                break;
            }
            if (image is BitmapSource)
            {
                using (var stream = new MemoryStream())
                {
                    encoder.Frames.Add(BitmapFrame.Create(image as BitmapSource));
                    encoder.Save(stream);
                    stream.Seek(0, SeekOrigin.Begin);
                    result = new byte[stream.Length];
                    var br = new BinaryReader(stream);
                    br.Read(result, 0, (int)stream.Length);
                }
            }

            return(result);
        }
예제 #10
0
        public static byte[] ImageSourceToBytes(ImageSource image, string preferredFormat)
        {
            byte[]        result  = null;
            BitmapEncoder encoder = null;

            switch (preferredFormat.ToLower())
            {
            case "jpg":
            case "jpeg":
                encoder = new JpegBitmapEncoder();
                break;

            case "bmp":
                encoder = new BmpBitmapEncoder();
                break;

            case "png":
                encoder = new PngBitmapEncoder();
                break;

            case "tif":
            case "tiff":
                encoder = new TiffBitmapEncoder();
                break;

            case "gif":
                encoder = new GifBitmapEncoder();
                break;

            case "wmp":
                encoder = new WmpBitmapEncoder();
                break;
            }

            if (image is BitmapSource)
            {
                MemoryStream stream = new MemoryStream();
                encoder.Frames.Add(BitmapFrame.Create(image as BitmapSource));
                encoder.Save(stream);
                stream.Seek(0, SeekOrigin.Begin);
                result = new byte[stream.Length];
                BinaryReader br = new BinaryReader(stream);
                br.Read(result, 0, (int)stream.Length);
                br.Close();
                stream.Close();
            }
            return(result);
        }
예제 #11
0
        public static void SaveImage(string filename, BitmapSource bitmapSource)
        {
            if (string.IsNullOrEmpty(filename))
            {
                return;
            }
            var           imageType = Path.GetExtension(filename).Trim('.');
            BitmapEncoder encoder;

            switch (imageType.ToLower())
            {
            case "png":
                encoder = new PngBitmapEncoder();
                break;

            case "jpg":
            case "jpeg":
                encoder = new JpegBitmapEncoder();
                break;

            case "bmp":
                encoder = new BmpBitmapEncoder();
                break;

            case "tiff":
                encoder = new TiffBitmapEncoder();
                break;

            case "gif":
                encoder = new GifBitmapEncoder();
                break;

            case "wmb":
                encoder = new WmpBitmapEncoder();
                break;

            default:
                return;
            }

            using (var fileStream = new FileStream(filename, FileMode.Create))
            {
                encoder.Frames.Add(BitmapFrame.Create(bitmapSource));
                encoder.Save(fileStream);
            }
        }
예제 #12
0
        public static void Save(this BitmapSource source, Stream stream, BitmapEncoding enc, BitmapMetadata data)
        {
            BitmapEncoder encorder = null;

            switch (enc)
            {
            case BitmapEncoding.Bmp:
                encorder = new BmpBitmapEncoder();
                break;

            case BitmapEncoding.Png:
                encorder = new PngBitmapEncoder();
                break;

            case BitmapEncoding.Jpg:
                encorder = new JpegBitmapEncoder();
                break;

            case BitmapEncoding.Tiff:
                encorder = new TiffBitmapEncoder();
                break;

            case BitmapEncoding.Gif:
                encorder = new GifBitmapEncoder();
                break;

            case BitmapEncoding.Wmp:
                encorder = new WmpBitmapEncoder();
                break;

            case BitmapEncoding.Icon:
                throw new NotSupportedException("The icon format can only load!");

            default:
                throw new NotImplementedException();
            }

            encorder.Frames.Add(BitmapFrame.Create(source));
            if (data != null)
            {
                encorder.Metadata = data;
            }
            encorder.Save(stream);
        }
예제 #13
0
 private void ConvertHDPhoto(PackagePart part)
 {
     using (Stream stream = part.GetStream())
     {
         BitmapDecoder    bitmapDecoder    = BitmapDecoder.Create(stream, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
         WmpBitmapEncoder wmpBitmapEncoder = new WmpBitmapEncoder();
         for (int i = 0; i < bitmapDecoder.Frames.Count; i++)
         {
             BitmapFrame item = BitmapFrame.Create(bitmapDecoder.Frames[i]);
             wmpBitmapEncoder.Frames.Add(item);
         }
         using (MemoryStream memoryStream = new MemoryStream())
         {
             wmpBitmapEncoder.Save(memoryStream);
             stream.SetLength(0L);
             memoryStream.Seek(0L, SeekOrigin.Begin);
             memoryStream.CopyTo(stream);
         }
     }
 }
예제 #14
0
        public static void FileToWmp(string inFile, string outFile, float f)
        {
            // Container for bitmap frames
            BitmapDecoder bdFile = null;
            // Read the source file into a FileStream object
            FileStream readFile = File.OpenRead(inFile);

            // Set the BitmapDecoder object from the source file
            bdFile = BitmapDecoder.Create(readFile, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
            // Prepare the output file
            FileStream writeFile = File.OpenWrite(outFile);
            // All the magic done by WmpBitmapEncoder
            WmpBitmapEncoder wbeFile = new WmpBitmapEncoder();

            // Set the quality level to... pretty good
            wbeFile.ImageQualityLevel = f;
            // Add the bitmap frame to the encoder object
            wbeFile.Frames.Add(bdFile.Frames[0]);
            // Write the output file
            wbeFile.Save(writeFile);
            writeFile.Close();
            readFile.Close();
        }
예제 #15
0
        /// <summary>
        /// Encodes the image data.
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="encoding">The encoding.</param>
        /// <returns></returns>
        private byte[] EncodeImageData(ImageSource image, ImageEncoding encoding)
        {
            byte[] buffer        = null;
            var    bitmapEncoder = (BitmapEncoder)null;

            switch (encoding)
            {
            case ImageEncoding.Jpg100:
                bitmapEncoder = new JpegBitmapEncoder
                {
                    QualityLevel = 100
                };
                break;

            case ImageEncoding.Jpg95:
                bitmapEncoder = new JpegBitmapEncoder
                {
                    QualityLevel = 95
                };
                break;

            case ImageEncoding.Jpg90:
                bitmapEncoder = new JpegBitmapEncoder
                {
                    QualityLevel = 90
                };
                break;

            case ImageEncoding.Jpg:
                bitmapEncoder = new JpegBitmapEncoder();
                break;

            case ImageEncoding.Gif:
                bitmapEncoder = new GifBitmapEncoder();
                break;

            case ImageEncoding.Png:
                bitmapEncoder = new PngBitmapEncoder();
                break;

            case ImageEncoding.Tiff:
                bitmapEncoder = new TiffBitmapEncoder();
                break;

            case ImageEncoding.Bmp:
                bitmapEncoder = new BmpBitmapEncoder();
                break;

            case ImageEncoding.Wmp:
                bitmapEncoder = new WmpBitmapEncoder();
                break;
            }

            if (image is BitmapSource)
            {
                using (var memoryStream = new MemoryStream())
                {
                    if (bitmapEncoder != null)
                    {
                        var bitmapFrame = BitmapFrame.Create(image as BitmapSource);
                        bitmapEncoder.Frames.Add(bitmapFrame);
                        bitmapEncoder.Save(memoryStream);
                    }
                    memoryStream.Seek(0L, SeekOrigin.Begin);
                    buffer = new byte[memoryStream.Length];
                    using (var binaryReader = new BinaryReader(memoryStream))
                    {
                        binaryReader.Read(buffer, 0, (int)memoryStream.Length);
                    }
                }
            }

            return(buffer);
        }
예제 #16
0
        public override void Set(string key, object value, CacheItemPolicy policy, string regionName = null)
        {
            var bitmap = value as BitmapFrame;

            if (bitmap == null)
            {
                throw new ArgumentException("The parameter value must contain a System.Windows.Media.Imaging.BitmapFrame.");
            }

            var           metadata = (BitmapMetadata)bitmap.Metadata;
            var           format   = metadata != null ? metadata.Format : "bmp";
            BitmapEncoder encoder  = null;

            switch (format)
            {
            case "bmp":
                encoder = new BmpBitmapEncoder();
                break;

            case "gif":
                encoder = new GifBitmapEncoder();
                break;

            case "jpg":
                encoder = new JpegBitmapEncoder();
                break;

            case "png":
                encoder = new PngBitmapEncoder();
                break;

            case "tiff":
                encoder = new TiffBitmapEncoder();
                break;

            case "wmphoto":
                encoder = new WmpBitmapEncoder();
                break;

            default:
                break;
            }

            if (encoder == null)
            {
                throw new NotSupportedException(string.Format("The bitmap format {0} is not supported.", format));
            }

            memoryCache.Set(key, bitmap, policy, regionName);

            var path = string.Format("{0}.{1}", GetPath(key), format);

            try
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));

                using (var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    encoder.Frames.Add(bitmap);
                    encoder.Save(fileStream);
                }

                var fileSecurity = File.GetAccessControl(path);
                fileSecurity.AddAccessRule(fullControlRule);
                File.SetAccessControl(path, fileSecurity);
            }
            catch (Exception ex)
            {
                Debug.WriteLine("ImageFileCache: Writing file {0} failed: {1}", path, ex.Message);
            }
        }
예제 #17
0
        private void ThreadFunction()
        {
            BitmapImage       img;
            TransformedBitmap transformed;
            ScaleTransform    trasform;
            BitmapEncoder     enc;
            FileStream        trgstream;
            string            target;

            try
            {
                if (!Directory.Exists(PictureConverter.ConvOptions.TargetDir))
                {
                    Directory.CreateDirectory(PictureConverter.ConvOptions.TargetDir);
                }
            }
            catch (Exception) { return; }


            for (int i = 0; i < _sourcefiles.Count; i++)
            {
                try
                {
                    img = new BitmapImage();
                    img.BeginInit();
                    img.UriSource = new Uri(_sourcefiles[i]);
                    img.EndInit();
                    img.Freeze();

                    switch (PictureConverter.ConvOptions.SizeMode)
                    {
                    case SizeingMode.Percent:
                        trasform = new ScaleTransform(PictureConverter.ConvOptions.Percent, PictureConverter.ConvOptions.Percent);
                        break;

                    case SizeingMode.BoxFit:
                        double zoomratio = Math.Min((double)PictureConverter.ConvOptions.Height / img.PixelHeight, (double)PictureConverter.ConvOptions.Width / img.PixelWidth);
                        trasform = new ScaleTransform(zoomratio, zoomratio);
                        break;

                    case SizeingMode.NoChange:
                    default:
                        trasform = new ScaleTransform(1, 1);
                        break;
                    }

                    transformed = new TransformedBitmap(img, trasform);

                    target = CreateOutName(_sourcefiles[i]);
                    if (File.Exists(target))
                    {
                        File.Delete(target);
                    }
                    trgstream = File.Create(target);

                    switch (PictureConverter.ConvOptions.OutputFormat)
                    {
                    case ImageFormat.Jpeg:
                        enc = new JpegBitmapEncoder();
                        (enc as JpegBitmapEncoder).QualityLevel = PictureConverter.ConvOptions.Quality;
                        enc.Frames.Add(BitmapFrame.Create(transformed));
                        enc.Save(trgstream);
                        break;

                    case ImageFormat.Bmp:
                        enc = new BmpBitmapEncoder();
                        if (PictureConverter.ConvOptions.PixelFormat != PixFormat.Nochange)
                        {
                            enc.Frames.Add(BitmapFrame.Create(ColorConv(transformed)));
                        }
                        else
                        {
                            enc.Frames.Add(BitmapFrame.Create(transformed));
                        }
                        enc.Save(trgstream);
                        break;

                    case ImageFormat.Png:
                        enc = new PngBitmapEncoder();
                        if (PictureConverter.ConvOptions.PixelFormat != PixFormat.Nochange)
                        {
                            enc.Frames.Add(BitmapFrame.Create(ColorConv(transformed)));
                        }
                        else
                        {
                            enc.Frames.Add(BitmapFrame.Create(transformed));
                        }
                        enc.Save(trgstream);
                        break;

                    case ImageFormat.Gif:
                        enc = new GifBitmapEncoder();
                        enc.Frames.Add(BitmapFrame.Create(transformed));
                        enc.Save(trgstream);
                        break;

                    case ImageFormat.Tiff:
                        enc = new TiffBitmapEncoder();
                        if (PictureConverter.ConvOptions.PixelFormat != PixFormat.Nochange)
                        {
                            enc.Frames.Add(BitmapFrame.Create(ColorConv(transformed)));
                        }
                        else
                        {
                            enc.Frames.Add(BitmapFrame.Create(transformed));
                        }
                        enc.Save(trgstream);
                        break;

                    case ImageFormat.Wmp:
                        enc = new WmpBitmapEncoder();
                        (enc as WmpBitmapEncoder).QualityLevel = (byte)PictureConverter.ConvOptions.Quality;
                        enc.Frames.Add(BitmapFrame.Create(transformed));
                        enc.Save(trgstream);
                        break;
                    }
                    trgstream.Close();
                }
                catch (Exception)
                {
                    _error.Add(_sourcefiles[i]);
                }
                ++_cntr;
            }
            _isfinished = true;
        }
예제 #18
0
        private byte[] EncodeImageData(ImageSource image, ImageEncoding encoding)
        {
            byte[]        buffer  = null;
            BitmapEncoder encoder = null;

            switch (encoding)
            {
            case ImageEncoding.Jpg100:
                encoder = new JpegBitmapEncoder {
                    QualityLevel = 100
                };
                break;

            case ImageEncoding.Jpg95:
                encoder = new JpegBitmapEncoder {
                    QualityLevel = 95
                };
                break;

            case ImageEncoding.Jpg90:
                encoder = new JpegBitmapEncoder {
                    QualityLevel = 90
                };
                break;

            case ImageEncoding.Jpg:
                encoder = new JpegBitmapEncoder();
                break;

            case ImageEncoding.Bmp:
                encoder = new BmpBitmapEncoder();
                break;

            case ImageEncoding.Png:
                encoder = new PngBitmapEncoder();
                break;

            case ImageEncoding.Tiff:
                encoder = new TiffBitmapEncoder();
                break;

            case ImageEncoding.Gif:
                encoder = new GifBitmapEncoder();
                break;

            case ImageEncoding.Wmp:
                encoder = new WmpBitmapEncoder();
                break;
            }
            if (image is BitmapSource)
            {
                var stream = new MemoryStream();
                if (encoder != null)
                {
                    var bitmapFrame = BitmapFrame.Create(image as BitmapSource);
                    encoder.Frames.Add(bitmapFrame);
                    encoder.Save(stream);
                }
                stream.Seek(0L, SeekOrigin.Begin);
                buffer = new byte[stream.Length];
                var reader = new BinaryReader(stream);
                reader.Read(buffer, 0, (int)stream.Length);
                reader.Close();
                stream.Close();
            }
            return(buffer);
        }
예제 #19
0
        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            mainWindow       = new Window();
            mainWindow.Title = "WDP Imaging Sample";
            ScrollViewer mySV = new ScrollViewer();

            //<Snippet4>
            int width  = 128;
            int height = width;
            int stride = width / 8;

            byte[] pixels = new byte[height * stride];

            // Define the image palette
            BitmapPalette myPalette = BitmapPalettes.WebPalette;

            // Creates a new empty image with the pre-defined palette

            //<Snippet2>
            BitmapSource image = BitmapSource.Create(
                width,
                height,
                96,
                96,
                PixelFormats.Indexed1,
                myPalette,
                pixels,
                stride);
            //</Snippet2>

            //<Snippet3>
            FileStream       stream      = new FileStream("new.wdp", FileMode.Create);
            WmpBitmapEncoder encoder     = new WmpBitmapEncoder();
            TextBlock        myTextBlock = new TextBlock();

            myTextBlock.Text = "Codec Author is: " + encoder.CodecInfo.Author.ToString();
            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);
            //</Snippet3>
            //</Snippet4>

            //<Snippet1>

            // Open a Stream and decode a WDP image
            Stream           imageStreamSource = new FileStream("tulipfarm.wdp", FileMode.Open, FileAccess.Read, FileShare.Read);
            WmpBitmapDecoder decoder           = new WmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource     bitmapSource      = decoder.Frames[0];

            // Draw the Image
            Image myImage = new Image();

            myImage.Source  = bitmapSource;
            myImage.Stretch = Stretch.None;
            myImage.Margin  = new Thickness(20);
            //</Snippet1>

            //<Snippet5>

            // Open a Uri and decode a WDP image
            Uri myUri = new Uri("tulipfarm.wdp", UriKind.RelativeOrAbsolute);
            WmpBitmapDecoder decoder3      = new WmpBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource     bitmapSource3 = decoder3.Frames[0];

            // Draw the Image
            Image myImage2 = new Image();

            myImage2.Source  = bitmapSource3;
            myImage2.Stretch = Stretch.None;
            myImage2.Margin  = new Thickness(20);
            //</Snippet5>

            //<Snippet6>
            FileStream        stream2       = new FileStream("tulipfarm.jpg", FileMode.Open);
            JpegBitmapDecoder decoder2      = new JpegBitmapDecoder(stream2, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
            BitmapSource      bitmapSource2 = decoder2.Frames[0];
            FileStream        stream3       = new FileStream("new2.wdp", FileMode.Create);
            WmpBitmapEncoder  encoder2      = new WmpBitmapEncoder();

            encoder2.Frames.Add(BitmapFrame.Create(bitmapSource2));
            encoder2.Save(stream3);
            //</Snippet6>

            // Define a StackPanel to host the decoded WDP images
            StackPanel myStackPanel = new StackPanel();

            myStackPanel.Orientation         = Orientation.Vertical;
            myStackPanel.VerticalAlignment   = VerticalAlignment.Stretch;
            myStackPanel.HorizontalAlignment = HorizontalAlignment.Stretch;

            // Add the Image and TextBlock to the parent Grid
            myStackPanel.Children.Add(myImage);
            myStackPanel.Children.Add(myImage2);
            myStackPanel.Children.Add(myTextBlock);

            // Add the StackPanel as the Content of the Parent Window Object
            mySV.Content       = myStackPanel;
            mainWindow.Content = mySV;
            mainWindow.Show();
        }
예제 #20
0
        private void OnSaveImpl(
            Document input,
            Stream output,
            SaveConfigToken token,
            Surface scratchSurface,
            ProgressEventHandler callback)
        {
            HDPhotoSaveConfigToken hdToken = token as HDPhotoSaveConfigToken;
            WmpBitmapEncoder       wbe     = new WmpBitmapEncoder();

            using (RenderArgs ra = new RenderArgs(scratchSurface))
            {
                input.Render(ra, true);
            }

            MemoryBlock block = scratchSurface.Scan0;
            IntPtr      scan0 = block.Pointer;

            double dpiX;
            double dpiY;

            switch (input.DpuUnit)
            {
            case MeasurementUnit.Centimeter:
                dpiX = Document.DotsPerCmToDotsPerInch(input.DpuX);
                dpiY = Document.DotsPerCmToDotsPerInch(input.DpuY);
                break;

            case MeasurementUnit.Inch:
                dpiX = input.DpuX;
                dpiY = input.DpuY;
                break;

            case MeasurementUnit.Pixel:
                dpiX = Document.GetDefaultDpu(MeasurementUnit.Inch);
                dpiY = Document.GetDefaultDpu(MeasurementUnit.Inch);
                break;

            default:
                throw new InvalidEnumArgumentException();
            }

            BitmapSource bitmapSource = BitmapFrame.Create(
                scratchSurface.Width,
                scratchSurface.Height,
                dpiX,
                dpiY,
                System.Windows.Media.PixelFormats.Bgra32,
                null,
                scan0,
                (int)block.Length, // TODO: does not support >2GB images
                scratchSurface.Stride);

            FormatConvertedBitmap fcBitmap = new FormatConvertedBitmap(
                bitmapSource,
                hdToken.BitDepth == 24 ? PixelFormats.Bgr24 : PixelFormats.Bgra32,
                null,
                0);

            BitmapFrame outputFrame0 = BitmapFrame.Create(fcBitmap);

            wbe.Frames.Add(outputFrame0);
            wbe.ImageQualityLevel = (float)hdToken.Quality / 100.0f;

            string tempFileName = FileSystem.GetTempFileName();

            FileStream tempFileOut = new FileStream(tempFileName, FileMode.Create, FileAccess.Write, FileShare.Read);

            wbe.Save(tempFileOut);
            tempFileOut.Close();
            tempFileOut = null;

            FileStream                  tempFileIn = new FileStream(tempFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
            WmpBitmapDecoder            wbd        = new WmpBitmapDecoder(tempFileIn, BitmapCreateOptions.None, BitmapCacheOption.None);
            BitmapFrame                 ioFrame0   = wbd.Frames[0];
            InPlaceBitmapMetadataWriter metadata2  = ioFrame0.CreateInPlaceBitmapMetadataWriter();

            CopyMetadataTo(metadata2, input.Metadata);
            tempFileIn.Close();
            tempFileIn = null;

            FileStream tempFileIn2 = new FileStream(tempFileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);

            Utility.CopyStream(tempFileIn2, output);
            tempFileIn2.Close();
            tempFileIn2 = null;

            try
            {
                File.Delete(tempFileName);
            }

            catch (Exception)
            {
            }

            // WPF doesn't give us an IDisposable implementation on its types
            Utility.GCFullCollect();
        }
예제 #21
0
        private void CreateAndShowMainWindow()
        {
            // Create the application's main window
            _mainWindow = new Window {
                Title = "WDP Imaging Sample"
            };
            var mySv = new ScrollViewer();

            var width  = 128;
            var height = width;
            var stride = width / 8;
            var pixels = new byte[height * stride];

            // Define the image palette
            var myPalette = BitmapPalettes.WebPalette;

            // Creates a new empty image with the pre-defined palette

            var image = BitmapSource.Create(
                width,
                height,
                96,
                96,
                PixelFormats.Indexed1,
                myPalette,
                pixels,
                stride);

            var stream      = new FileStream("new.wdp", FileMode.Create);
            var encoder     = new WmpBitmapEncoder();
            var myTextBlock = new TextBlock {
                Text = "Codec Author is: " + encoder.CodecInfo.Author
            };

            encoder.Frames.Add(BitmapFrame.Create(image));
            encoder.Save(stream);


            // Open a Stream and decode a WDP image
            Stream imageStreamSource = new FileStream("tulipfarm.wdp", FileMode.Open, FileAccess.Read, FileShare.Read);
            var    decoder           = new WmpBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat,
                                                            BitmapCacheOption.Default);
            BitmapSource bitmapSource = decoder.Frames[0];

            // Draw the Image
            var myImage = new Image
            {
                Source  = bitmapSource,
                Stretch = Stretch.None,
                Margin  = new Thickness(20)
            };


            // Open a Uri and decode a WDP image
            var myUri    = new Uri("tulipfarm.wdp", UriKind.RelativeOrAbsolute);
            var decoder3 = new WmpBitmapDecoder(myUri, BitmapCreateOptions.PreservePixelFormat,
                                                BitmapCacheOption.Default);
            BitmapSource bitmapSource3 = decoder3.Frames[0];

            // Draw the Image
            var myImage2 = new Image
            {
                Source  = bitmapSource3,
                Stretch = Stretch.None,
                Margin  = new Thickness(20)
            };

            var stream2  = new FileStream("tulipfarm.jpg", FileMode.Open);
            var decoder2 = new JpegBitmapDecoder(stream2, BitmapCreateOptions.PreservePixelFormat,
                                                 BitmapCacheOption.Default);
            BitmapSource bitmapSource2 = decoder2.Frames[0];
            var          stream3       = new FileStream("new2.wdp", FileMode.Create);
            var          encoder2      = new WmpBitmapEncoder();

            encoder2.Frames.Add(BitmapFrame.Create(bitmapSource2));
            encoder2.Save(stream3);

            // Define a StackPanel to host the decoded WDP images
            var myStackPanel = new StackPanel
            {
                Orientation         = Orientation.Vertical,
                VerticalAlignment   = VerticalAlignment.Stretch,
                HorizontalAlignment = HorizontalAlignment.Stretch
            };

            // Add the Image and TextBlock to the parent Grid
            myStackPanel.Children.Add(myImage);
            myStackPanel.Children.Add(myImage2);
            myStackPanel.Children.Add(myTextBlock);

            // Add the StackPanel as the Content of the Parent Window Object
            mySv.Content        = myStackPanel;
            _mainWindow.Content = mySv;
            _mainWindow.Show();
        }