Beispiel #1
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageFormatInformation"/> struct.
 /// </summary>
 /// <param name="decoder">The decoder.</param>
 /// <param name="description">The description.</param>
 /// <param name="filter">The filter.</param>
 public ImageFormatInformation(ImageDecoder decoder, string description, string filter)
 {
     Decoder     = decoder;
     Encoder     = null;
     Description = description;
     Filter      = filter;
 }
Beispiel #2
0
 public ImageFormatInformation(ImageDecoder decoder, string description, string filter)
 {
     this.Decoder     = decoder;
     this.Encoder     = null;
     this.Description = description;
     this.Filter      = filter;
 }
Beispiel #3
0
        private void MenuSaveOnClick(object sender, EventArgs e)
        {
            if (_saveFileDialog.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }
            ImageEncoder encoder = null;

            switch (_saveFileDialog.FilterIndex)
            {
            case 1:
                //for more control over saving, use the PdfCollection and PdfImage classes
                encoder = new PdfEncoder();
                break;

            case 2:
                encoder = new TiffEncoder();
                break;

            case 3:
                encoder = new JpegEncoder();
                break;
            }
            _workspaceViewer.Save(_saveFileDialog.FileName, encoder);
        }
Beispiel #4
0
        /// <summary>
        ///     Embeds the secret image in the OriginalImage.
        /// </summary>
        public async Task EmbedSecretImage(bool encrypt)
        {
            var secretImageData = this.EncryptedSecretImage != null
                ? await ImageUtilities.GetImageData(this.EncryptedSecretImage)
                : await ImageUtilities.GetImageData(this.SecretImage);

            var originalImageData = await ImageUtilities.GetImageData(this.OriginalImage);

            var imageEncoder = new ImageEncoder();

            byte[] modifiedImageData;

            if (encrypt)
            {
                modifiedImageData =
                    imageEncoder.EncodeImage(originalImageData, this.OriginalImage.PixelWidth,
                                             secretImageData, this.OriginalImage.PixelWidth, this.OriginalImage.PixelHeight);
            }
            else
            {
                modifiedImageData =
                    imageEncoder.EncodeImage(originalImageData, this.OriginalImage.PixelWidth,
                                             secretImageData, this.SecretImage.PixelWidth, this.SecretImage.PixelHeight);
            }

            modifiedImageData = HeaderUtilities.AddHeader(modifiedImageData, this.OriginalImage.PixelWidth, encrypt, 1,
                                                          MessageType.MonochromeBmp);

            this.ModifiedImage    = new WriteableBitmap(this.OriginalImage.PixelWidth, this.OriginalImage.PixelHeight);
            using var writeStream = this.ModifiedImage.PixelBuffer.AsStream();
            await writeStream.WriteAsync(modifiedImageData, 0, modifiedImageData.Length);
        }
Beispiel #5
0
        public void LearningInLayerTest(int width, int height, string imageName)
        {
            // Prepare test output folder
            var outFolder = EnsureFolderExist(nameof(ImageEncoderTest));

            // Prepare input file for test
            string inputImage = Path.Combine("TestFiles", imageName);

            // Initialize Image Encoder
            ImageEncoder encoder = new ImageEncoder(new BinarizerParams {
                ImageWidth = width, ImageHeight = height
            });

            // Initialize HTMModules
            int       inputBits  = width * height;
            int       numColumns = 1024;
            HtmConfig cfg        = new HtmConfig(new int[] { inputBits }, new int[] { numColumns });
            var       mem        = new Connections(cfg);

            SpatialPoolerMT sp = new SpatialPoolerMT();

            sp.Init(mem);

            CortexLayer <object, object> layer1 = new CortexLayer <object, object>("L1");

            layer1.HtmModules.Add("encoder", encoder);
            layer1.HtmModules.Add("sp", sp);

            //Test Compute method
            var computeResult  = layer1.Compute(inputImage, true) as int[];
            var activeCellList = GetActiveCells(computeResult);

            Debug.WriteLine($"Active Cells computed from Image {inputImage}: {activeCellList}");
        }
Beispiel #6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageFormatInformation"/> struct.
 /// </summary>
 /// <param name="encoder">The encoder.</param>
 /// <param name="description">The description.</param>
 /// <param name="filter">The filter.</param>
 public ImageFormatInformation(ImageEncoder encoder, string description, string filter)
 {
     Encoder     = encoder;
     Decoder     = null;
     Description = description;
     Filter      = filter;
 }
Beispiel #7
0
        /// <inheritdoc />
        public Task Save(CompressedBitmapFormat format, float quality, Stream target)
        {
            ImageEncoder encoder        = null;
            int          qualityPercent = (int)(100 * quality);

            switch (format)
            {
            case CompressedBitmapFormat.Jpeg:
                encoder = new JpegEncoder();
                ((JpegEncoder)encoder).Quality = qualityPercent;
                break;

            case CompressedBitmapFormat.Png:
                encoder = new PngEncoder();
                if (qualityPercent == 100)
                {
                    ((PngEncoder)encoder).Compression = PngCompression.None;
                }
                else if (qualityPercent < 10)
                {
                    ((PngEncoder)encoder).Compression = PngCompression.Level1;
                }
                else
                {
                    ((PngEncoder)encoder).Compression = (PngCompression)(qualityPercent / 10);
                }

                break;
            }

            encoder.SetResolution(new Tizen.Multimedia.Size((int)Width, (int)Height));
            return(encoder.EncodeAsync(Inner.Buffer, target));
        }
 /// <summary>
 /// 将 Direct2D 位图保存到文件中。
 /// </summary>
 /// <param name="image">要保存的位图。</param>
 /// <param name="fileName">要保存的文件名。</param>
 public void SaveBitmapToFile(Bitmap image, string fileName)
 {
     using (ImagingFactory2 factory = new ImagingFactory2())
     {
         using (WICStream stream = new WICStream(factory, fileName, NativeFileAccess.Write))
         {
             using (BitmapEncoder encoder = new PngBitmapEncoder(factory))
             {
                 encoder.Initialize(stream);
                 using (BitmapFrameEncode bitmapFrameEncode = new BitmapFrameEncode(encoder))
                 {
                     bitmapFrameEncode.Initialize();
                     int width  = image.PixelSize.Width;
                     int height = image.PixelSize.Height;
                     bitmapFrameEncode.SetSize(width, height);
                     Guid wicPixelFormat = WICPixelFormat;
                     bitmapFrameEncode.SetPixelFormat(ref wicPixelFormat);
                     using (ImageEncoder imageEncoder = new ImageEncoder(factory, this.d2DDevice))
                     {
                         imageEncoder.WriteFrame(image, bitmapFrameEncode,
                                                 new ImageParameters(D2PixelFormat, 96, 96, 0, 0, width, height));
                         bitmapFrameEncode.Commit();
                         encoder.Commit();
                     }
                 }
             }
         }
     }
 }
Beispiel #9
0
        /// <summary>
        /// Updates the image info label.
        /// </summary>
        /// <param name="newImage"></param>
        private void updateImageInfo(Image newImage)
        {
            int    numberOfPixels  = ImageEncoder.getNumberOfPixels(newImage);
            int    numberOfLetters = ImageEncoder.getNumberOfLetters(numberOfPixels);
            String info            = "The image is " + numberOfPixels + " pixels large. It can store " + numberOfLetters + " letters. Note, the letter contraint is set by the encryption algos used by this software. Different algos can yield a different limit.";

            pictureInfoLabel.Text = info;
        }
Beispiel #10
0
        /// <summary>
        /// Called when the user tries to save after encoding
        /// </summary>
        private void encodeSave(ImageEncoder decodedImage)
        {
            String filePath = saveOutput("Image Files(*.bmp)|*.bmp");

            if (filePath.Length > 0)
            {
                decodedImage.saveImageToFile(filePath);
            }
        }
Beispiel #11
0
        public void EncodeImage()
        {
            // Crop a slightly different interior region of the same size and verify that the data is different (as a sanity check)
            EncodedImage encImg = new EncodedImage();

            ImageEncoder.EncodeFrom(encImg, this.testImage, new PngBitmapEncoder());
            Image target = new Image(this.testImage.Width, this.testImage.Height, this.testImage.Stride, this.testImage.PixelFormat);

            ImageDecoder.DecodeTo(encImg, target);
            this.AssertAreImagesEqual(this.testImage, target);
        }
Beispiel #12
0
 private void encode(Image image, String encryptionKeyText, String positionSeedText, String message)
 {
     if ((message.Length > 0 && encryptionKeyText.Length > 0) && positionSeedText.Length > 0)
     {
         switchPage(pages[ImageEncoderView.OUTPUTPAGEINDEX]);    // switch to the output page
         outputImageEncoderVar = new ImageEncoder(image, "bmp"); // assume bmp for now
         outputImageEncoderVar.embedMessage(message, encryptionKeyText, positionSeedText);
         changeImageInBox(outputPreview, outputImageEncoderVar.Image, maxImagePreviewSize);
         outputImageEncoderVar.saveImageToFile("C:/Users/navba/Desktop/newImage.bmp");
     }
 }
Beispiel #13
0
 /// <summary>
 /// Write the image to a file
 /// </summary>
 /// <param name="filename">The destination filename for the image</param>
 /// <param name="format">The image format to store the image in</param>
 public void SaveImage(string filename, ImageFormat format)
 {
     if (markings.Count > 0)
     {
         ImageEncoder.EncodeImage(filename, format, width, height, pixels, markings.ToArray());
     }
     else
     {
         ImageEncoder.EncodeImage(filename, format, width, height, pixels);
     }
 }
 private static void AddSeperatelyLicensedEncoderFormat(ImageEncoder encoder, string description, string filter)
 {
     try
     {
         EncoderImageFormats.Add(new ImageFormatInformation(encoder, description, filter));
     }
     catch (AtalasoftLicenseException e)
     {
         MessageBox.Show(null, string.Format(@"{0}; {1}", encoder, e), Resources.WinDemoHelperMethods_CoderLicenseError_Caption);
     }
 }
Beispiel #15
0
        public static bool HaveEncoder(ImageEncoder enc)
        {
            foreach (ImageFormatInformation info in _encoderImageFormats)
            {
                if (enc.GetType().Equals(info.GetType()))
                {
                    return(true);
                }
            }

            return(false);
        }
        public async Task EmbedMessage(
            string fileInputLocation,
            string fileOutputLocation,
            string message,
            string password)
        {
            try
            {
                ConsoleLogger.LogMessage("Creating encoder instance...");
                ImageEncoder imageEncoder = new ImageEncoder(
                    format: ImageFormat.Png,
                    encryptionConfiguration: new EncryptionConfiguration(EncryptionType.Aes256, 20000),
                    compressionConfiguration: new CompressionConfiguration(CompressionType.Gzip, CompressionLevel.Standard),
                    embeddedImage: new EmbeddedImage(Image.FromFile(fileInputLocation), EmbeddedImage.PixelStorage.Auto)
                    );
                ConsoleLogger.LogMessage("Reading message bytes...");
                byte[] contentBytes    = Encoding.UTF8.GetBytes(message);
                string outputDirectory = Path.GetDirectoryName(fileOutputLocation);
                if (!Directory.Exists(outputDirectory))
                {
                    Directory.CreateDirectory(outputDirectory);
                }
                ConsoleLogger.LogMessage("Appending message bytes into a memory stream...");
                MemoryStream contentStream = new MemoryStream();
                await contentStream.WriteAsync(contentBytes, 0, contentBytes.Length);

                ConsoleLogger.LogMessage("Adding memory stream object into encoder...");
                imageEncoder.AddDirectory(new Input.Directory("\\", new[]
                {
                    new Input.File("__payload__.bin", contentStream)
                }));
                using (FileStream outputStream = new FileStream(fileOutputLocation, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    ConsoleLogger.LogMessage("Encoding data into target image...");
                    ConsoleLogger.LogMessage("Creating output image...");
                    await imageEncoder.SaveAsync(
                        outputStream : outputStream,
                        encodingConfiguration : new EncodingConfiguration
                        (
                            password: password,
                            tempStorageProvider: new MemoryStorageProvider(),
                            bufferSize: 81920,
                            fileGroupSize: 1024 * 1024
                        ));

                    ConsoleLogger.LogMessage($"Operation succeeded. File saved at {fileOutputLocation}");
                }
            }
            catch (Exception ex)
            {
                ConsoleLogger.ShowErrorMessage(ex.Message);
            }
        }
        public async Task EmbedFiles(
            string fileInputLocation,
            string fileOutputLocation,
            string[] fileAttachments,
            string password)
        {
            try
            {
                ConsoleLogger.LogMessage("Creating encoder instance...");
                ImageEncoder imageEncoder = new ImageEncoder(
                    format: ImageFormat.Png,
                    encryptionConfiguration: new EncryptionConfiguration(EncryptionType.Aes256, 20000),
                    compressionConfiguration: new CompressionConfiguration(CompressionType.Gzip, CompressionLevel.Standard),
                    embeddedImage: new EmbeddedImage(Image.FromFile(fileInputLocation), EmbeddedImage.PixelStorage.Auto)
                    );
                string outputDirectory = Path.GetDirectoryName(fileOutputLocation);
                if (!Directory.Exists(outputDirectory))
                {
                    Directory.CreateDirectory(outputDirectory);
                }

                string attachmentDirectory = Path.GetDirectoryName(fileAttachments.FirstOrDefault());

                ConsoleLogger.LogMessage("Adding file(s) into encoder instance...");
                List <Input.File> files = new List <Input.File>();
                foreach (string file in fileAttachments)
                {
                    files.Add(new Input.File(new System.IO.FileInfo(file)));
                }
                imageEncoder.AddDirectory(new Input.Directory("\\", files));

                using (FileStream outputStream = new FileStream(fileOutputLocation, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    ConsoleLogger.LogMessage("Encoding data into target image...");
                    ConsoleLogger.LogMessage("Creating output image...");
                    await imageEncoder.SaveAsync(
                        outputStream : outputStream,
                        encodingConfiguration : new EncodingConfiguration
                        (
                            password: password,
                            tempStorageProvider: new MemoryStorageProvider(),
                            bufferSize: 81920,
                            fileGroupSize: 1024 * 1024
                        ));

                    ConsoleLogger.LogMessage($"Operation succeeded. File saved at {fileOutputLocation}");
                }
            }
            catch (Exception ex)
            {
                ConsoleLogger.ShowErrorMessage(ex.ToString());
            }
        }
        /// <summary>
        /// Performs the file save... note that annotaitons are automatically embedded
        /// if the target encoder supports embedded annotations
        /// </summary>
        /// <param name="fileName"></param>
        private void SaveImageFile(string fileName)
        {
            ImageEncoder enc = GetEncoder(Path.GetExtension(fileName));

            if (enc != null)
            {
                this.documentAnnotationViewer1.Save(fileName, enc);
            }
            else
            {
                MessageBox.Show("unable to determine correct encoder for file: " + fileName);
            }
        }
        private async Task CreateVersionCompatData(
            ImageFormat format,
            FileInfo inputZipFIle,
            EncryptionConfiguration encryption,
            CompressionConfiguration compression,
            EmbeddedImage embeddedImage)
        {
            var    inputFileName = Path.GetFileNameWithoutExtension(inputZipFIle.Name);
            string outputName    = inputFileName.Substring(0, Math.Min(inputFileName.Length, 10)) + "-" + Enum.GetName(typeof(ImageFormat), format);

            if (embeddedImage != null)
            {
                outputName += "-E";
            }

            if (encryption != null)
            {
                outputName += "-" + Enum.GetName(typeof(EncryptionType), encryption.Type).Substring(0, 3);
            }

            if (compression != null)
            {
                outputName += "-" + Enum.GetName(typeof(CompressionType), compression.Type).Substring(0, 3);
            }


            var tempInputDataDirectory = _ouputTempVersionDataDirectory.CreateSubdirectory(outputName + "_original_data");

            using (var zipFile = ZipFile.Read(inputZipFIle.FullName))
            {
                zipFile.ExtractAll(tempInputDataDirectory.FullName);
            }


            DirectoryInfo outputDirectory = _ouputTempVersionDataDirectory.CreateSubdirectory(outputName);
            var           encoder         = new ImageEncoder(format, encryption, compression, embeddedImage);

            using (Stream encodedImageFile = File.Create(Path.Combine(outputDirectory.FullName, inputFileName + "." + encoder.Extension)))
            {
                encoder.AddDirectory(tempInputDataDirectory);
                await encoder.SaveAsync(encodedImageFile, new EncodingConfiguration(
                                            password : "******",
                                            tempStorageProvider : new MemoryStorageProvider(),
                                            bufferSize : 4096,
                                            fileGroupSize : 1024 * 500));

                inputZipFIle.CopyTo(Path.Combine(outputDirectory.FullName, "Original_Data.zip"), true);
            }

            tempInputDataDirectory.Delete(true);
        }
Beispiel #20
0
 private void decode(Image image, String encryptionKeyText, String positionSeedText)
 {
     if (encryptionKeyText.Length > 0 && positionSeedText.Length > 0)
     {
         switchPage(pages[ImageEncoderView.OUTPUTPAGEINDEX]);       // switch to the output page
         ImageEncoder imageEncode = new ImageEncoder(image, "bmp"); // assume bmp for now
         outputMessageVar = imageEncode.decrypt(encryptionKeyText, positionSeedText, -1);
         if (outputMessageVar.Length == 0)
         {
             outputMessageVar = "The image could not be succesfully. Maybe you have the wrong encryption key and/or position seed.";
         }
         outputMessage.Text = outputMessageVar;
     }
 }
        public async Task EncodingThenDecoding_ProducesEquivalentResults(
            ImageFormat format,
            FileInfo inputZipFile,
            EncryptionConfiguration encryption,
            CompressionConfiguration compression,
            EmbeddedImage embeddedImage,
            IDictionary <string, string> metadata)
        {
            DirectoryInfo inputDirectory  = null;
            DirectoryInfo outputDirectory = null;

            try
            {
                using (var storageStream = new MemoryStream())
                {
                    inputDirectory = _inputRootDirectory.CreateSubdirectory(Path.GetFileNameWithoutExtension(inputZipFile.Name));
                    using (var zipFile = ZipFile.Read(inputZipFile.FullName))
                    {
                        zipFile.ExtractAll(inputDirectory.FullName);
                    }

                    var encoder = new ImageEncoder(format, encryption, compression, embeddedImage);

                    encoder.Metadata = metadata;
                    encoder.AddDirectory(inputDirectory);
                    await encoder.SaveAsync(storageStream, ImageConfigurations.EncodingConfiguration);

                    storageStream.Position = 0;

                    var decoder = await ImageDecoder.LoadAsync(storageStream, ImageConfigurations.DecodingConfiguration);

                    outputDirectory = _ouputRootDirectory.CreateSubdirectory(inputDirectory.Name);
                    await decoder.DecodeAsync(outputDirectory);

                    AssertEx.AreEqualByJson(metadata, decoder.Metadata);
                    DirectoryAssert.AreEquivalent(inputDirectory, outputDirectory);
                }
            }
            finally
            {
                foreach (var directory in new[] { inputDirectory, outputDirectory })
                {
                    if (directory != null)
                    {
                        directory.Delete(true);
                    }
                }
            }
        }
        private void SetEncoder(string extension)
        {
            ImageEncoder encoder = this.FindEncoder(extension);

            if (encoder == null)
            {
                encoder = this.FindEncoder("png");
            }
            Tracer.Assert(encoder != null);
            if (this.Encoder != encoder)
            {
                this.Encoder = encoder;
                this.NotifyPropertyChanged("Encoder");
            }
        }
Beispiel #23
0
        public void ImageEncoderTest(int width, int height, string imageName)
        {
            var outFolder = EnsureFolderExist(nameof(ImageEncoderTest));

            string inputImage = Path.Combine("TestFiles", imageName);

            ImageEncoder encoder = new ImageEncoder(new BinarizerParams {
                ImageWidth = width, ImageHeight = height
            });

            int[] encodedValue = encoder.Encode(inputImage);

            encoder.EncodeAndSaveAsImage(inputImage, Path.Combine(outFolder, $"encodedImage_{imageName}"));

            encoder.EncodeAndSave(inputImage, Path.Combine(outFolder, $"encodedImage_{Path.GetFileNameWithoutExtension(imageName)}.txt"));
        }
        public async Task CS_W_ImageProcessor_ImageEncoder()
        {
            var processor = new ImageProcessor();

            var sample1 = new MediaSample2D(MediaSample2DFormat.Nv12, 320, 240);
            var sample2 = processor.Rotate(sample1, BitmapRotation.Clockwise90Degrees);
            var sample3 = processor.Convert(sample2, MediaSample2DFormat.Bgra8, 480, 640);

            var file1 = await KnownFolders.PicturesLibrary.CreateFileAsync("CS_W_ImageProcessor_ImageEncoder1.jpg", CreationCollisionOption.ReplaceExisting);

            await ImageEncoder.SaveToFileAsync(sample1, file1, ImageCompression.Jpeg);

            var file2 = await KnownFolders.PicturesLibrary.CreateFileAsync("CS_W_ImageProcessor_ImageEncoder2.jpg", CreationCollisionOption.ReplaceExisting);

            await sample2.SaveToFileAsync(file2, ImageCompression.Jpeg);
        }
Beispiel #25
0
        /// <summary>
        ///     Encrypts the modified image.
        /// </summary>
        public async Task EncryptSecretImage()
        {
            if (this.SecretImage == null)
            {
                return;
            }

            var encryptedSecretImageData = ImageEncoder.EncryptImage(
                await ImageUtilities.GetImageData(this.SecretImage), this.OriginalImage.PixelWidth,
                this.OriginalImage.PixelHeight, this.SecretImage.PixelWidth, this.SecretImage.PixelHeight);

            this.EncryptedSecretImage =
                new WriteableBitmap(this.OriginalImage.PixelWidth, this.OriginalImage.PixelHeight);

            using var writeStream = this.EncryptedSecretImage.PixelBuffer.AsStream();
            await writeStream.WriteAsync(encryptedSecretImageData, 0, encryptedSecretImageData.Length);
        }
        /// <summary>
        ///
        /// </summary>
        private void SaveCurrentImage()
        {
            //show the save dialog
            m_SaveFileDialog.DefaultExt  = "tga";
            m_SaveFileDialog.FilterIndex = 5;
            m_SaveFileDialog.Filter      = HelperMethods.CreateDialogFilter(false);

            if (m_SaveFileDialog.ShowDialog() == DialogResult.OK)
            {
                ImageType    imageType    = HelperMethods.GetImageType(m_SaveFileDialog.FilterIndex, false);
                ImageEncoder imageEncoder = HelperMethods.GetEncoderFromType(imageType);

                if (imageEncoder != null)
                {
                    WorkspaceViewer.Save(m_SaveFileDialog.FileName, imageEncoder);
                }
            }
        }
Beispiel #27
0
        private void Initialize()
        {
            _d2dFactory   = new SharpDX.Direct2D1.Factory1();
            DWriteFactory = new SharpDX.DirectWrite.Factory1();
            WicFactory    = new ImagingFactory2();

            DevicePixelFormat = new SharpDX.Direct2D1.PixelFormat(SharpDX.DXGI.Format.R8G8B8A8_UNorm, AlphaMode.Premultiplied);
            ImagePixelFormat  = SharpDX.WIC.PixelFormat.Format32bppPRGBA;
            using (var defaultDevice = new SharpDX.Direct3D11.Device(DriverType.Hardware, DeviceCreationFlags.BgraSupport))
                using (var d3dDevice = defaultDevice.QueryInterface <SharpDX.Direct3D11.Device1>())
                    using (var dxgiDevice = d3dDevice.QueryInterface <SharpDX.DXGI.Device2>())
                    {
                        _d2dDevice    = new SharpDX.Direct2D1.Device(_d2dFactory, dxgiDevice);
                        DeviceContext = new SharpDX.Direct2D1.DeviceContext(_d2dDevice, new DeviceContextOptions());
                    }

            WicImageEncoder = new ImageEncoder(WicFactory, _d2dDevice);
            DeviceContext.TextAntialiasMode = SharpDX.Direct2D1.TextAntialiasMode.Grayscale;
        }
Beispiel #28
0
        internal unsafe void Read(Stream stream, int resourceSize)
        {
            switch (GetIconImageFormat(stream))
            {
            case IconImageFormat.BMP:
            {
                mEncoder = new BMPEncoder();
                mEncoder.Read(stream, resourceSize);
                break;
            }

            case IconImageFormat.PNG:
            {
                mEncoder = new PNGEncoder();
                mEncoder.Read(stream, resourceSize);
                break;
            }
            }
        }
Beispiel #29
0
    public ImageEncoder(Image imageParameter, String imageTypeParameter)
    {
        ImageEncoder.intializeOffsetList(); // initializes the offset list for image encoder

        image     = imageParameter;
        imageType = imageTypeParameter;

        if (imageOffset.ContainsKey(imageType)) // make sure it's an acceptable type
        {
            bytes      = DataManipulation.imageToByteList(image, imageType);
            binaryList = DataManipulation.convertByteListToBinaryList(bytes, byteSize);
            imageOffset.TryGetValue(imageType, out byteOffset); // will assign byteOffset to the byteOffset parameter
            numberOfPixels = (bytes.Count - byteOffset) / 3;    // each pixel is three bytes
        }
        else
        {
            throw new Exception("The image type of " + imageType + " is not an acceptable type.");
        }
    }
Beispiel #30
0
        /// <summary>
        ///     Extracts the secret image from a ModifiedImage.
        /// </summary>
        public async Task ExtractSecretImage()
        {
            var modifiedImageData = await ImageUtilities.GetImageData(this.ModifiedImage);

            if (HeaderUtilities.IsMessageEmbedded(modifiedImageData, this.ModifiedImage.PixelWidth) &&
                HeaderUtilities.GetMessageType(modifiedImageData, this.ModifiedImage.PixelWidth) ==
                MessageType.MonochromeBmp)
            {
                var imageEncoder = new ImageEncoder();

                var secretImageData =
                    imageEncoder.DecodeImage(modifiedImageData, this.ModifiedImage.PixelWidth,
                                             this.ModifiedImage.PixelHeight);

                this.SecretImage = new WriteableBitmap(this.ModifiedImage.PixelWidth, this.ModifiedImage.PixelHeight);

                if (!HeaderUtilities.IsEncrypted(modifiedImageData, this.ModifiedImage.PixelWidth))
                {
                    using var writeStream = this.SecretImage.PixelBuffer.AsStream();
                    await writeStream.WriteAsync(secretImageData, 0, secretImageData.Length);

                    this.EncryptedSecretImage = null;
                }
                else
                {
                    this.EncryptedSecretImage =
                        new WriteableBitmap(this.ModifiedImage.PixelWidth, this.ModifiedImage.PixelHeight);
                    using var encryptedWriteStream = this.EncryptedSecretImage.PixelBuffer.AsStream();
                    await encryptedWriteStream.WriteAsync(secretImageData, 0, secretImageData.Length);

                    using var writeStream = this.SecretImage.PixelBuffer.AsStream();
                    await writeStream.WriteAsync(ImageUtilities.SwitchImageHalves(secretImageData), 0,
                                                 secretImageData.Length);
                }
            }
            else
            {
                throw new ArgumentException("Modified Image doesn't contain Secret Image");
            }
        }