Beispiel #1
0
        /// <summary>
        ///     Converts an RGBAImage object into a byte array that can be loaded into a texture.
        /// </summary>
        /// <param name="image">The Imgae object to convert.</param>
        /// <param name="format">The resulting texture format/compression.</param>
        /// <param name="mipmaps">Whether to generate mipmaps for the texture.</param>
        /// <returns>
        ///     A byte array that can be loaded into a Unity Texture2D.
        /// </returns>
        public static byte[] ImageToTexture(RGBAImage image, TextureCompressionFormat format = TextureCompressionFormat.DXT5, bool mipmaps = true)
        {
            // Retrieve the raw pixel data from the image.
            byte[] srcBytes = new byte[image.Size];
            image.CopyRawData(srcBytes);

            /*
             * Allocate a handle for the pixel data so that it doesn't get garbage collected.
             * This will allow a the pixel array to be reprsented as an pointer so that it
             * can be used by the Nvidia Texture Tools.
             */
            GCHandle pinnedArray = GCHandle.Alloc(srcBytes, GCHandleType.Pinned);
            IntPtr   srcBytesPtr = pinnedArray.AddrOfPinnedObject();

            /*
             * Initialize an array to store the generated data with a size of zero. The array
             * will be resized as needed. A wrapper is used so that the array can be resized
             * within the lambda callback expression in the OutputOptions.
             */
            BytesWrapper destBytes = new BytesWrapper()
            {
                Bytes = new byte[0]
            };

            InputOptions       inputOptions       = GenerateInputOptions(srcBytesPtr, image.Width, image.Height, mipmaps);
            CompressionOptions compressionOptions = GenerateCompressionOptions(format);
            OutputOptions      outputOptions      = GenerateOutputOptions(destBytes);

            Compressor compressor = new Compressor();

            compressor.Compress(inputOptions, compressionOptions, outputOptions);

            // Free the allocated handle so that it be garbage collected.
            pinnedArray.Free();

            return(destBytes.Bytes);
        }