Example #1
0
        /// <summary>
        /// 1bppのイメージを圧縮してTifで保存する ( mono 1bpp image(uncompressed)→ save mono 1bpp .bmp(compressed))
        /// </summary>
        /// <param name="img">圧縮保存する画像s</param>
        /// <param name="fimeName">ファイル名</param>
        /// <param name="compressionScheme">圧縮方法指定パラメータ</param>
        public static void SaveComp1bppTif(Bitmap img, string fileName, EncoderValue compressionScheme)
        {
            if (compressionScheme != EncoderValue.CompressionCCITT3 &&
                    compressionScheme != EncoderValue.CompressionCCITT4 &&
                    compressionScheme != EncoderValue.CompressionLZW &&
                    compressionScheme != EncoderValue.CompressionNone &&
                    compressionScheme != EncoderValue.CompressionRle)
            {
                throw new ArgumentException("compressionScheme");
            }

            //TIFFのImageCodecInfoを取得する
            ImageCodecInfo ici = GetEncoderInfo("image/tiff");
            if (ici == null)
            {
                return;
            }

            //圧縮方法指定
            EncoderParameters encParam = new EncoderParameters(1);
            encParam.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)compressionScheme);

            //画像保存
            img.Save(fileName, ici, encParam);

            //後片付け
            encParam.Dispose();
            encParam = null;

            return;

        }
        /// <summary>
        /// This function will join the TIFF file with a specific compression format
        /// </summary>
        /// <param name="imageFiles">string array with source image files</param>
        /// <param name="outFile">target TIFF file to be produced</param>
        /// <param name="compressEncoder">compression codec enum</param>
        public void JoinTiffImages(string[] imageFiles, string outFile)
        {
            EncoderValue compressEncoder = EncoderValue.CompressionLZW;

            try
            {
                //If only one page in the collection, copy it directly to the target file.
                if (imageFiles.Length == 1)
                {
                    File.Copy(imageFiles[0], outFile, true);
                    return;
                }

                //use the save encoder
                Encoder enc = Encoder.SaveFlag;

                EncoderParameters ep = new EncoderParameters(2);
                ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
                ep.Param[1] = new EncoderParameter(Encoder.Compression, (long)compressEncoder);

                Bitmap         pages = null;
                int            frame = 0;
                ImageCodecInfo info  = GetEncoderInfo("image/tiff");


                foreach (string strImageFile in imageFiles)
                {
                    if (frame == 0)
                    {
                        pages = (Bitmap)Image.FromFile(strImageFile);

                        //save the first frame
                        pages.Save(outFile, info, ep);
                    }
                    else
                    {
                        //save the intermediate frames
                        ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);

                        Bitmap bm = (Bitmap)Image.FromFile(strImageFile);
                        pages.SaveAdd(bm, ep);
                    }

                    if (frame == imageFiles.Length - 1)
                    {
                        //flush and close.
                        ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
                        pages.SaveAdd(ep);
                    }

                    frame++;
                }
            }
            catch (Exception)
            {
                throw;
            }

            return;
        }
        /// <summary>
        /// 把多页的tiff文件分页,返回Bitmap图像数组。
        /// </summary>
        /// <param name="images">Bitmap图像数组</param>
        /// <param name="format">图像编码格式</param>
        public void SplitTiffImage(out Bitmap[] images, EncoderValue format)
        {
            images = new Bitmap[this._PageNumber];
            try
            {
                Guid           objGuid      = image.FrameDimensionsList[0];
                FrameDimension objDimension = new FrameDimension(objGuid);

                int number = 0;
                //Saves every frame as a separate file.
                Encoder enc = Encoder.Compression;
                for (int i = 0; i < _PageNumber; i++)
                {
                    image.SelectActiveFrame(objDimension, number);
                    EncoderParameters ep = new EncoderParameters(1);
                    ep.Param[0] = new EncoderParameter(enc, (long)format);
                    ImageCodecInfo info = GetEncoderInfo("image/tiff");

                    images[number] = (Bitmap)image.Clone();
                    number++;
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Example #4
0
        /// <summary>
        /// This function will output the image to a TIFF file with specific compression format
        /// </summary>
        /// <param name="outPutDirectory">The splited images' directory</param>
        /// <param name="format">The codec for compressing</param>
        /// <returns>splited file name array list</returns>
        public ArrayList SplitTiffImage(string outPutDirectory, EncoderValue format)
        {
            string fileStartString  = outPutDirectory + "\\" + GetFileNameStartString();
            var    splitedFileNames = new ArrayList();
            Guid   objGuid          = image.FrameDimensionsList[0];
            var    objDimension     = new FrameDimension(objGuid);

            //Saves every frame as a separate file.
            Encoder enc      = Encoder.Compression;
            int     curFrame = 0;

            for (int i = 0; i < number; i++)
            {
                image.SelectActiveFrame(objDimension, curFrame);
                var ep = new EncoderParameters(1);
                ep.Param[0] = new EncoderParameter(enc, (long)format);
                ImageCodecInfo info = GetEncoderInfo("image/tiff");

                //Save the master bitmap
                string fileName = string.Format("{0}{1}.TIF", fileStartString, i);
                image.Save(fileName, info, ep);
                splitedFileNames.Add(fileName);

                curFrame++;
            }

            return(splitedFileNames);
        }
        //Define JoinTiffImages() method to save the images from PDF pages to tiff image type, with the specified encoder and image-encoder parameters.
        public static void JoinTiffImages(Image[] images, string outFile, EncoderValue compressEncoder)
        {
            Encoder           enc = Encoder.SaveFlag;
            EncoderParameters ep  = new EncoderParameters(2);

            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
            ep.Param[1] = new EncoderParameter(Encoder.Compression, (long)compressEncoder);
            Image          pages = images[0];
            int            frame = 0;
            ImageCodecInfo info  = GetEncoderInfo("image/tiff");

            foreach (Image img in images)
            {
                if (frame == 0)
                {
                    pages = img;
                    pages.Save(outFile, info, ep);
                }

                else
                {
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);

                    pages.SaveAdd(img, ep);
                }
                if (frame == images.Length - 1)
                {
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
                    pages.SaveAdd(ep);
                }
                frame++;
            }
        }
Example #6
0
        public static void JoinTiffImages(Image[] images, string outFile, EncoderValue compressEncoder)
        {
            //Use the save encoder
            System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;
            EncoderParameters ep = new EncoderParameters(2);

            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
            ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)compressEncoder);
            Image          pages = images[0];
            int            frame = 0;
            ImageCodecInfo info  = GetEncoderInfo("image/tiff");

            foreach (Image img in images)
            {
                if (frame == 0)
                {
                    pages = img;
                    //Save the first frame
                    pages.Save(outFile, info, ep);
                }
                else
                {
                    //Save the intermediate frames
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);
                    pages.SaveAdd(img, ep);
                }
                if (frame == images.Length - 1)
                {
                    //Flush and close.
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
                    pages.SaveAdd(ep);
                }
                frame++;
            }
        }
Example #7
0
        /// <summary>
        /// This function will join the TIFF file with a specific compression format
        /// </summary>
        /// <param name="imageFiles">array list with source image files</param>
        /// <param name="outFile">target TIFF file to be produced</param>
        /// <param name="compressEncoder">compression codec enum</param>
        public void JoinTiffImages(ArrayList imageFiles, string outFile, EncoderValue compressEncoder)
        {
            try
            {
                //If only one page in the collection, copy it directly to the target file.
                if (imageFiles.Count == 1)
                {
                    File.Copy((string)(imageFiles[0]), outFile, true);
                    return;
                }

                //use the save encoder
                System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;

                EncoderParameters ep = new EncoderParameters(2);
                ep.Param[0] = new EncoderParameter(enc, System.Convert.ToInt64(EncoderValue.MultiFrame));
                ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, System.Convert.ToInt64(compressEncoder));

                Bitmap         pages = null;
                int            frame = 0;
                ImageCodecInfo info  = GetEncoderInfo("image/tiff");


                foreach (string strImageFile in imageFiles)
                {
                    if (frame == 0)
                    {
                        pages = (Bitmap)(Image.FromFile(strImageFile));

                        //save the first frame
                        pages.Save(outFile, info, ep);
                    }
                    else
                    {
                        //save the intermediate frames
                        ep.Param[0] = new EncoderParameter(enc, System.Convert.ToInt64(EncoderValue.FrameDimensionPage));

                        Bitmap bm = (Bitmap)(Image.FromFile(strImageFile));
                        pages.SaveAdd(bm, ep);
                        bm.Dispose();
                    }

                    if (frame == imageFiles.Count - 1)
                    {
                        //flush and close.
                        ep.Param[0] = new EncoderParameter(enc, System.Convert.ToInt64(EncoderValue.Flush));
                        pages.SaveAdd(ep);
                    }

                    frame += 1;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return;
        }
Example #8
0
		/// <summary>
		/// Convert the existing TIFF to a different codec format
		/// </summary>
		/// <param name="compressEncoder"></param>
		/// <returns></returns>
		public void ConvertTiffFormat(string strNewImageFileName,EncoderValue compressEncoder)
		{
			//Split the image files to single pages.
			ArrayList arrSplited=SplitTiffImage(this._TempWorkingDir,compressEncoder);
			JoinTiffImages(arrSplited,strNewImageFileName,compressEncoder);

			return;
		}
Example #9
0
        private static Image TransformJpeg(Image image, EncoderValue transformationCode)
        {
            EncoderParameters encoderParams = new EncoderParameters(1);

            encoderParams.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Transformation, (long)transformationCode);
            byte[] imageBytes = ImageTools.EncodeImageParams(image, ImageFormat.Jpeg, encoderParams);
            return(ImageFromByteArray(imageBytes));
        }
Example #10
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageExport"/> class.
 /// </summary>
 public ImageExport()
 {
     FImageFormat               = ImageExportFormat.Jpeg;
     FSeparateFiles             = true;
     Resolution                 = 96;
     FJpegQuality               = 100;
     FMonochromeTiffCompression = EncoderValue.CompressionCCITT4;
 }
Example #11
0
        public EncoderParameters CreateTIFFEncoder(EncoderValue CompressionType)
        {
            System.Drawing.Imaging.Encoder _Encoder = System.Drawing.Imaging.Encoder.Compression;

            EncoderParameters _EncoderParameteres = new EncoderParameters(1);
            EncoderParameter  _EncoderParameter   = new EncoderParameter(_Encoder, (long)CompressionType);

            _EncoderParameteres.Param[0] = _EncoderParameter;

            return(_EncoderParameteres);
        }
Example #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ImageExport"/> class.
 /// </summary>
 public ImageExport()
 {
     paddingNonSeparatePages = 10;
     fileSuffix                = String.Empty;
     HasMultipleFiles          = true;
     imageFormat               = ImageExportFormat.Jpeg;
     separateFiles             = true;
     Resolution                = 96;
     jpegQuality               = 100;
     monochromeTiffCompression = EncoderValue.CompressionCCITT4;
 }
        public static void JoinTiffImages(Image image, string outFile, EncoderValue compressEncoder)
        {
            //Use the save encoder
            Encoder           enc = Encoder.SaveFlag;
            EncoderParameters ep  = new EncoderParameters(2);

            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
            ep.Param[1] = new EncoderParameter(Encoder.Compression, (long)compressEncoder);
            //Get the information of tiff type
            ImageCodecInfo info = GetEncoderInfo("image/tiff");

            //Save to image
            image.Save(outFile, info, ep);
        }
Example #14
0
        /// <summary>
        /// Remove a specific page within the image object and save the result to an output image file.
        /// </summary>
        /// <param name="pageNumber">page number to be removed</param>
        /// <param name="compressEncoder">compress encoder after operation</param>
        /// <param name="strFileName">filename to be outputed</param>
        /// <param name="ratio"></param>
        public void RemoveAPage(int pageNumber, EncoderValue compressEncoder, string strFileName, float ratio)
        {
            //Split the image files to single pages.
            ArrayList arrSplited = SplitTiffImage(tempWorkingDir, compressEncoder);

            //Remove the specific page from the collection
            string strPageRemove = string.Format("{0}\\{1}{2}.TIF", tempWorkingDir, GetFileNameStartString(), pageNumber);

            arrSplited.Remove(strPageRemove);

            JoinTiffImages(arrSplited, strFileName, compressEncoder, ratio);

            return;
        }
Example #15
0
        private void threadCode(EncoderValue compressionMethod)
        {
            List <string> ItemsToProcess = new List <string>();

            ImageCodecInfo codecInfo = GetEncoderInfo("image/tiff");

            if (Directory.Exists(inputTextbox.Text))
            {
                foreach (string file in Directory.GetFiles(inputTextbox.Text))
                {
                    if (Path.GetExtension(file) == ".tiff" || Path.GetExtension(file) == ".tif")
                    {
                        ItemsToProcess.Add(file);
                    }
                }

                progressBar1.BeginInvoke(new MethodInvoker(() =>
                {
                    progressBar1.Maximum = ItemsToProcess.Count();
                    progressBar1.Value   = 0;
                }));

                List <Action> tasks = new List <Action>();
                for (int i = 0; i <= ItemsToProcess.Count() - 1; i++)
                {
                    string inputPath  = ItemsToProcess[i];
                    string OutputPath = outputTextBox.Text + @"\" + Path.GetFileName(ItemsToProcess[i]);
                    if (!File.Exists(OutputPath))
                    {
                        tasks.Add(() => recompress(inputPath, OutputPath, codecInfo, compressionMethod));
                    }
                }
                Parallel.Invoke(new ParallelOptions()
                {
                    MaxDegreeOfParallelism = Properties.Settings.Default.CPUThreads
                }, tasks.ToArray());
                RecompressButton.BeginInvoke(new MethodInvoker(() =>
                {
                    RecompressButton.Enabled          = true;
                    inputTextbox.Enabled              = true;
                    outputTextBox.Enabled             = true;
                    browseInput.Enabled               = true;
                    browseOutput.Enabled              = true;
                    compressionMethodComboBox.Enabled = true;
                    CPUThreads.Enabled = true;
                }));
                MessageBox.Show("Recompression finished!");
            }
        }
Example #16
0
        private void RecompressButton_Click(object sender, EventArgs e)
        {
            inputTextbox.Enabled              = false;
            outputTextBox.Enabled             = false;
            browseInput.Enabled               = false;
            browseOutput.Enabled              = false;
            compressionMethodComboBox.Enabled = false;
            RecompressButton.Enabled          = false;
            CPUThreads.Enabled = false;
            if (!Directory.Exists(outputTextBox.Text))
            {
                Directory.CreateDirectory(outputTextBox.Text);
            }
            EncoderValue compressionMethod = getCompressionMethod(compressionMethodComboBox.SelectedItem.ToString());

            System.Threading.Thread thread = new System.Threading.Thread(() => threadCode(compressionMethod));
            thread.Start();
        }
Example #17
0
		/// <summary>
		/// Remove a specific page within the image object and save the result to an output image file.
		/// </summary>
		/// <param name="pageNumber">page number to be removed</param>
		/// <param name="compressEncoder">compress encoder after operation</param>
		/// <param name="strFileName">filename to be outputed</param>
		/// <returns></</returns>
		public void RemoveAPage(int pageNumber,EncoderValue compressEncoder,string strFileName){
			try
			{
				//Split the image files to single pages.
				ArrayList arrSplited=SplitTiffImage(this._TempWorkingDir,compressEncoder);
				
				//Remove the specific page from the collection
				string strPageRemove=string.Format("{0}\\{1}{2}.TIF",_TempWorkingDir,GetFileNameStartString(this._ImageFileName),pageNumber);
				arrSplited.Remove(strPageRemove);

				JoinTiffImages(arrSplited,strFileName,compressEncoder);
			}
			catch(Exception)
			{
				throw;
			}

			return;
		}
Example #18
0
        private static void WriteMTIF(string fileTIFOut, List <Bitmap> bitmaps, long bitDepth)
        {
            Encoder        encoder     = Encoder.SaveFlag;
            ImageCodecInfo encoderInfo = ImageCodecInfo.GetImageEncoders().First(i => i.MimeType == "image/tiff");
            EncoderValue   compression = EncoderValue.CompressionLZW; // TODO: Verify

            using (MemoryStream outStream = new MemoryStream())
            {
                using (EncoderParameters encoderParameters = new EncoderParameters(3))
                {
                    encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)compression);
                    encoderParameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, bitDepth);
                    encoderParameters.Param[2] = new EncoderParameter(encoder, (long)EncoderValue.MultiFrame);
                    Bitmap firstBitmap = null;
                    for (int i = 0; i < bitmaps.Count; i++)
                    {
                        Bitmap bitmap = bitmaps[i];
                        if (i == 0)
                        {
                            firstBitmap = bitmap;
                            firstBitmap.Save(outStream, encoderInfo, encoderParameters);
                        }
                        else
                        {
                            encoderParameters.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.FrameDimensionPage);
                            firstBitmap.SaveAdd(bitmap, encoderParameters);
                        }
                    }
                    encoderParameters.Param[0] = new EncoderParameter(encoder, (long)EncoderValue.Flush);
                    firstBitmap.SaveAdd(encoderParameters);
                }
                outStream.Seek(0, SeekOrigin.Begin);
                using (Stream fileOutStream = File.Open(fileTIFOut, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
                {
                    outStream.CopyTo(fileOutStream);
                }
            }
        }
Example #19
0
 public static void JoinTiffImages(string DestinationPath, IEnumerable<byte[]> ImageFilesToJoin, EncoderValue CompressEncoder)
 {
     //use the overload and write all bytes
     File.WriteAllBytes(DestinationPath, JoinTiffImages(ImageFilesToJoin, CompressEncoder));
 }
Example #20
0
        public static byte[] JoinTiffImages(IEnumerable<byte[]> ImageFilesToJoin, EncoderValue CompressEncoder)
        {
            //create a memory stream to save
            using (var MemoryStreamToSave = new MemoryStream())
            {
                //if we only have 1 image then return that
                if (ImageFilesToJoin.Count() == 1)
                {
                    //go read the file and just return it
                    return ImageFilesToJoin.First();
                }

                //use the save encoder
                var EncoderToUse = System.Drawing.Imaging.Encoder.SaveFlag;

                //Encoder Parameter Array
                var EncodedParameters = new EncoderParameters(2);

                //Add the parameters to the array
                EncodedParameters.Param[0] = new EncoderParameter(EncoderToUse, (long)EncoderValue.MultiFrame);
                EncodedParameters.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)CompressEncoder);

                //Set the Encoder Info
                var EncoderInfo = GraphicsCommonUtilities.GetEncoderInfo("image/tiff");

                //go grab the first image and load it.
                using (var BaseImage = new MemoryStream(ImageFilesToJoin.First()))
                {
                    //create the image we will keep adding too as we add the rest of the images
                    using (var ImageToSave = (Bitmap)Image.FromStream(BaseImage))
                    {
                        //go save the first page of the image
                        ImageToSave.Save(MemoryStreamToSave, EncoderInfo, EncodedParameters);

                        //cache the frame count
                        int FirstPageFrameCount = GetImageFrameCount(ImageToSave);

                        //Set the parameter to be a next cont. page
                        EncodedParameters.Param[0] = new EncoderParameter(EncoderToUse, (long)EncoderValue.FrameDimensionPage);

                        //loop through the frames for this image
                        for (int i = 1; i < FirstPageFrameCount; i++)
                        {
                            //use the helper to add this specific frame to the image.
                            AddFrameToImage(ImageToSave, ImageToSave, i, EncodedParameters);
                        }

                        //now let's take care of the rest of the images now that we have the "base" image setup (skipping the first image because we took care of that already)
                        foreach (var ImageToAdd in ImageFilesToJoin.Skip(1))
                        {
                            //Grab it using the memory stream...we can dispose of this once we are done with this image
                            using (var MemoryStreamToUse = new MemoryStream(ImageToAdd))
                            {
                                //grab the bitmap image from the memory stream
                                using (var ImageToAddToTheBaseImage = (Bitmap)Image.FromStream(MemoryStreamToUse))
                                {
                                    //cache the frame count
                                    int FrameCount = GetImageFrameCount(ImageToAddToTheBaseImage);

                                    //now we need to loop though all the pages to add each page to the tiff we are using as the base tiff
                                    for (int i = 0; i < FrameCount; i++)
                                    {
                                        //use the helper to add this specific frame to the image.
                                        AddFrameToImage(ImageToSave, ImageToAddToTheBaseImage, i, EncodedParameters);
                                    }
                                }
                            }
                        }

                        //now that we are all done...we need to flush the image
                        EncodedParameters.Param[0] = new EncoderParameter(EncoderToUse, (long)EncoderValue.Flush);

                        //save the flush command
                        ImageToSave.SaveAdd(EncodedParameters);

                        //close the memory stream
                        MemoryStreamToSave.Flush();

                        //close the memory stream
                        MemoryStreamToSave.Close();

                        //return the byte array now
                        return MemoryStreamToSave.ToArray();
                    }
                }
            }
        }
Example #21
0
        /// <summary>
        /// 将给定的文件 拼接输出到指定的tif文件路径
        /// </summary>
        /// <param name="imageFiles">文件路径列表</param>
        /// <param name="outFile">拼接后保存的 tif文件路径</param>
        /// <param name="compressEncoder">压缩方式</param>
        public static void JoinTiffImages(List <string> imageFiles, string outFile, EncoderValue compressEncoder)
        {
            if (File.Exists(outFile))
            {
                File.Delete(outFile);
            }

            //如果只有一个文件,直接复制到目标
            if (imageFiles.Count == 1)
            {
                if (!File.Exists(imageFiles[0]))
                {
                    return;
                }

                File.Copy(imageFiles[0], outFile, true);
                return;
            }

            System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;

            EncoderParameters ep = new EncoderParameters(2);

            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
            ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)compressEncoder);

            Bitmap         pages = null;
            int            frame = 0;
            ImageCodecInfo info  = GetEncoderInfo("image/tiff");

            foreach (string strImageFile in imageFiles)
            {
                if (!File.Exists(strImageFile))
                {
                    continue;
                }

                if (frame == 0)
                {
                    pages = (Bitmap)Image.FromFile(strImageFile);
                    //保存第一个tif文件 到目标处
                    pages.Save(outFile, info, ep);
                }
                else
                {
                    //保存好第一个tif文件后,其余 设置为添加一帧到 图像中
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);

                    Bitmap bm = (Bitmap)Image.FromFile(strImageFile);
                    pages.SaveAdd(bm, ep);
                    bm.Dispose();
                }

                if (frame == imageFiles.Count - 1)
                {
                    //flush and close.
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
                    pages.SaveAdd(ep);
                }
                frame++;
            }
            pages.Dispose(); //释放资源
            return;
        }
Example #22
0
        /// <summary>
        /// This function will output the image
        /// to a TIFF file with specific compression format
        /// </summary>
        /// <param name="outPutDirectory">
        ///     The splited images' directory</param>
        /// <param name="format">The codec for compressing</param>
        /// <returns>splited file name array list</returns>
        public ArrayList SplitTiffImage(string outPutDirectory, EncoderValue format)
        {
            string fileStartString = outPutDirectory + "\\" +
                                     GetFileNameStartString(_ImageFileName);
            ArrayList splitedFileNames = new ArrayList();
            try
            {
                Guid objGuid = image.FrameDimensionsList[0];
                FrameDimension objDimension = new FrameDimension(objGuid);

                //Saves every frame as a separate file.
                Encoder enc = Encoder.Compression;
                int curFrame = 0;
                for (int i = 0; i < _PageNumber; i++)
                {
                    image.SelectActiveFrame(objDimension, curFrame);
                    EncoderParameters ep = new EncoderParameters(1);
                    ep.Param[0] = new EncoderParameter(enc, (long)format);
                    ImageCodecInfo info = GetEncoderInfo("image/tiff");

                    //Save the master bitmap
                    string fileName = string.Format("{0}{1}.TIF",
                           fileStartString, i.ToString());
                    image.Save(fileName, info, ep);
                    splitedFileNames.Add(fileName);
                    curFrame++;
                }
            }
            catch (Exception)
            {
                throw;
            }

            return splitedFileNames;
        }
Example #23
0
        /// <summary>
        /// Convert the existing TIFF to a different codec format
        /// </summary>
        /// <param name="compressEncoder"></param>
        /// <returns></returns>
        public void ConvertTiffFormat(string strNewImageFileName, EncoderValue compressEncoder)
        {
            //Split the image files to single pages.
            ArrayList arrSplited = SplitTiffImage(this._TempWorkingDir, compressEncoder);
            JoinTiffImages(arrSplited, strNewImageFileName, compressEncoder);

            return;
        }
Example #24
0
        /// <summary>
        /// This function will join the TIFF file with a specific compression format
        /// </summary>
        /// <param name="imageFiles">string array with source image files</param>
        /// <param name="outFile">target TIFF file to be produced</param>
        /// <param name="compressEncoder">compression codec enum</param>
        /// <param name="ratio"></param>
        public void JoinTiffImages(string[] imageFiles, string outFile, EncoderValue compressEncoder, float ratio)
        {
            //If only one page in the collection, copy it directly to the target file.
            if (imageFiles.Length == 1)
            {
                File.Copy(imageFiles[0], outFile, true);
                return;
            }

            //use the save encoder
            Encoder enc = Encoder.SaveFlag;

            var ep = new EncoderParameters(2);

            ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
            ep.Param[1] = new EncoderParameter(Encoder.Compression, (long)compressEncoder);

            Bitmap         pages = null;
            int            frame = 0;
            ImageCodecInfo info  = GetEncoderInfo("image/tiff");


            foreach (string strImageFile in imageFiles)
            {
                var img     = Image.FromFile(strImageFile);
                var nWidth  = (int)(img.Width * ratio);
                var nHeight = (int)(img.Height * ratio);
                var size    = new Size(nWidth, nHeight);

                if (frame == 0)
                {
                    pages = new Bitmap(img, size);
                    //save the first frame
                    pages.Save(outFile, info, ep);
                }
                else
                {
                    //save the intermediate frames
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);

                    var bm = new Bitmap(img, size);
                    if (pages != null)
                    {
                        pages.SaveAdd(bm, ep);
                    }
                }

                if (frame == imageFiles.Length - 1)
                {
                    //flush and close.
                    ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
                    if (pages != null)
                    {
                        pages.SaveAdd(ep);
                    }
                }

                frame++;
            }

            return;
        }
Example #25
0
        /// <summary>
        /// This function will output the image to a ImageFormat file
        /// </summary>
        /// <param name="outPutDirectory">The splited images' directory</param>
        /// <param name="format">The codec for compressing</param>
        /// <returns>splited file name array list</returns>
        public ArrayList SplitTiffImageToFormat(string outPutDirectory, EncoderValue format, ImageFormat imgFormat)
        {
            string fileStartString = outPutDirectory + "\\" + this.GetFileNameStartString(this.mImageFileName);
            ArrayList splitedFileNames = new ArrayList();
            try
            {
                Guid objGuid = this.image.FrameDimensionsList[0];
                FrameDimension objDimension = new FrameDimension(objGuid);

                //Saves every frame as a separate file.
                // Encoder enc = Encoder.Compression;
                int curFrame = 0;
                for (int i = 0; i < this.mPageNumber; i++)
                {
                    this.image.SelectActiveFrame(objDimension, curFrame);
                    using (Bitmap bmp = new Bitmap(this.image))
                    {
                        string saveFileName = String.Format("{0}{1}.{2}", fileStartString, i.ToString(), imgFormat.ToString());
                        bmp.Save(saveFileName, imgFormat);
                        splitedFileNames.Add(saveFileName);
                    }

                    curFrame++;
                }
            }
            catch (Exception)
            {
                throw;
            }

            return splitedFileNames;
        }
Example #26
0
        private void SaveAs(string filter, string encoder, EncoderValue encoderValue, Formats format)
        {
            saveFileDialog.Filter = filter;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                var encoderParameters = new EncoderParameters(1)
                {
                    Param = new[]
                    {
                        new EncoderParameter(Encoder.Compression, (long)encoderValue)
                    }
                };

                var stopwatch = new Stopwatch();
                stopwatch.Start();
                var stream = new FileStream(saveFileDialog.FileName, FileMode.Create);
                stopwatch.Stop();
                writingTime.Text = stopwatch.Elapsed.TotalMilliseconds + @" ms";

                stopwatch.Restart();
                image.Save(stream, GetEncoderInfo(encoder), encoderParameters);
                stopwatch.Stop();
                encodingTime.Text = stopwatch.Elapsed.TotalMilliseconds + @" ms";

                stream.Dispose();

                stopwatch.Restart();
                switch (format)
                {
                case Formats.BMP:
                    bmpImage = Image.FromFile(saveFileDialog.FileName);
                    break;

                case Formats.JPEG:
                    jpegImage = Image.FromFile(saveFileDialog.FileName);
                    break;

                case Formats.TIFF:
                    tiffImage = Image.FromFile(saveFileDialog.FileName);
                    break;

                default:
                    return;
                }

                stopwatch.Stop();
                readingTime.Text = stopwatch.Elapsed.TotalMilliseconds + @" ms";

                stopwatch.Restart();
                image.Save("test.bmp", GetEncoderInfo("image/bmp"), new EncoderParameters(1)
                {
                    Param = new[]
                    {
                        new EncoderParameter(Encoder.Compression, (long)EncoderValue.CompressionNone)
                    }
                });

                stopwatch.Stop();
                decodingTime.Text = stopwatch.Elapsed.TotalMilliseconds + @" ms";

                imageSizeAfterLabel.Text = new FileInfo(saveFileDialog.FileName).Length / 1024 + @" kb";
            }
        }
Example #27
0
        /// <summary>
        /// Overwrites the specified file on disk with a new version of the file rotated according
        /// to the specified Orientation.  Exceptions generated by an error writing the new file will
        /// bubble up from this method.
        ///
        /// Before the original file is overwritten, a copy is made in the temp files folder (so that
        /// the original image isn't lost if the write of the rotated version fails).  This temporary
        /// copy is deleted before the method returns if the write of the new rotated image is successful.
        /// </summary>
        /// <param name="filename">The fully-specified name of the file to rotate. </param>
        /// <param name="orientation">The orientation to apply to the rotated file. </param>
        public static void RotateAndSaveImageFile(string filename, Orientation orientation)
        {
            if (orientation == Orientation.Initial)
            {
                //No rotation was specified, so no need to change anything.
                return;
            }

            //Make a backup copy of the original image in the temp folder (so that if we hit a
            //failure during writing of the new image, both the original and new copies of the
            //image aren't gone).
            string backupFilename = GetBackupFilename(filename);

            System.IO.File.Copy(filename, backupFilename, true);

            //Since our original image is dependant on the existing file on disk to be saved,
            //we can't delete the original image file until the rotated image file is written.
            //Get a temporary file that we'll use below to write the new image data.
            string tempFilename = System.IO.Path.GetTempFileName();

            //Load the image from the specified filename
            using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                using (Image image = Image.FromStream(fileStream, true, false))
                {
                    //Calculate the new value for the EXIF rotation property, and set it on the image.  (This is
                    //calculated as the original EXIF rotation as read from the file, with the rotation performed
                    //in the app applied to that value.  Thus if the original EXIF rotation tag was incorrect,
                    //and the user manually rotated the image to be upright, the tag will continue to be incorrect.)
                    PropertyItem rotationPropertyItem         = image.GetPropertyItem(ROTATION_PROPERTY_ID);
                    Orientation  originalOrientation          = OrientationFromExifRotationPropertyValue(rotationPropertyItem.Value[0]);
                    Orientation  newOrientation               = (Orientation)((((int)originalOrientation) + ((int)orientation)) % 4);
                    int          newExifRotationPropertyValue = ExifRotationPropertyValueFromOrientation(newOrientation);
                    rotationPropertyItem.Value[0] = (byte)newExifRotationPropertyValue;
                    image.SetPropertyItem(rotationPropertyItem);

                    //Setup the EncoderParameters with the information that we will be performing when
                    //saving the rotated file.
                    EncoderParameters encoderParams        = new EncoderParameters(1);
                    EncoderValue      rotationEncoderValue = EncoderValueFromOrientation(orientation);
                    EncoderParameter  rotationParam        = new EncoderParameter(Encoder.Transformation, (long)rotationEncoderValue);
                    encoderParams.Param[0] = rotationParam;

                    //Setup the .jpg ImageCodecInfo that we need to save the rotated file.
                    ImageCodecInfo jpegCodecInfo = GetEncoderInfo("image/jpeg");

                    using (FileStream outFileStream = new FileStream(tempFilename, FileMode.Open, FileAccess.Write))
                    {
                        image.Save(outFileStream, jpegCodecInfo, encoderParams);
                    }
                }
            }

            //Delete the original image (making room for us to rename the new, rotated copy).
            System.IO.File.Delete(filename);

            try
            {
                //Now, move the rotated image that we saved out as a temporary file to the name and
                //location of the original file.
                File.Move(tempFilename, filename);
            }
            catch
            {
                //An error occurred moving the rotated file.  Try and retore the original file from
                //the copy that we saved in the temp folder, so that the file isn't just "gone" as
                //far as the user can tell.
                File.Move(backupFilename, filename);

                //Let the exception bubble up -- an error dialog will be displayed to the user.
                throw;
            }

            //Since we got to this point without an exception being thrown, the write of the new
            //file was apparently successful.  Delete the copy of the original file that we made
            //in the temp folder.
            System.IO.File.Delete(backupFilename);
        }
Example #28
0
        public void SaveTiffintoSingle(string outFile, EncoderValue compressEncoder)
        {
            //use for save image as single tiff
            int frame    = 0;
            int startPos = 0;
            int imgLen   = 0;

            byte[] recB = null;

            Closing exporting  = new Closing();
            bool    frontImage = false;

            exporting.Text            = "Exporting check images";
            exporting.lblCleanup.Text = "exporting check images to tiff...";
            exporting.Show();
            this.Cursor = Cursors.WaitCursor;
            int    reccnt = 0;
            string SingleTiffImagePath = string.Empty;

            try
            {
                foreach (x9Rec rec in x9Stuff)
                {
                    if (rec.recType == "50" && rec.recData.Substring(31, 1) == "0")
                    {
                        frontImage = true;
                    }
                    else if (rec.recType == "50" && rec.recData.Substring(31, 1) == "1")
                    {
                        frontImage = false;
                    }
                    if (rec.recImage.Trim().Length > 0)
                    {
                        startPos = System.Convert.ToInt32(rec.recImage.Substring(0, rec.recImage.IndexOf(",")));
                        imgLen   = System.Convert.ToInt32(rec.recImage.Substring(rec.recImage.IndexOf(",") + 1));
                        checkImageBR.BaseStream.Seek(startPos, SeekOrigin.Begin);
                        recB = new byte[imgLen + 1];
                        recB = checkImageBR.ReadBytes(imgLen);
                        if (!Directory.Exists(outFile))
                        {
                            Directory.CreateDirectory(outFile);
                        }
                        if (frontImage)
                        {
                            SingleTiffImagePath = frame + "F.tiff";
                        }
                        else
                        {
                            SingleTiffImagePath = frame + "R.tiff";
                            frame += 1;
                        }
                        if (File.Exists(Path.Combine(outFile, SingleTiffImagePath)))
                        {
                            File.Delete(Path.Combine(outFile, SingleTiffImagePath));
                        }
                        File.WriteAllBytes(Path.Combine(outFile, SingleTiffImagePath), recB);
                    }
                    reccnt += 1;
                    exporting.pbCleanup.Value = (int)(reccnt / (double)x9Stuff.Count) * 100;
                    Application.DoEvents();
                }
            }
            catch (Exception ex)
            {
                exporting.TopMost = false;
                MessageBox.Show(ex.Message + " rec count=" + reccnt.ToString("###,###,###"), "Error Exporting", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            exporting.Close();
            this.Cursor = Cursors.Default;
        }
Example #29
0
        public void JoinTiffImages3(string outFile, EncoderValue compressEncoder)
        {
            //use the save encoder
            System.Drawing.Imaging.Encoder enc = System.Drawing.Imaging.Encoder.SaveFlag;

            EncoderParameters ep = new EncoderParameters(2);

            ep.Param[0] = new EncoderParameter(enc, System.Convert.ToInt64(EncoderValue.MultiFrame));
            ep.Param[1] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, System.Convert.ToInt64(compressEncoder));

            Bitmap         pages    = null;
            int            frame    = 0;
            ImageCodecInfo info     = GetEncoderInfo("image/tiff");
            Image          cImg     = null;
            int            startPos = 0;
            int            imgLen   = 0;

            byte[] recB = null;

            Closing exporting  = new Closing();
            bool    frontImage = false;

            exporting.Text            = "Exporting check images";
            exporting.lblCleanup.Text = "exporting check images to tiff...";
            exporting.Show();
            this.Cursor = Cursors.WaitCursor;
            int reccnt = 0;

            try
            {
                foreach (x9Rec rec in x9Stuff)
                {
                    if (rec.recType == "50" && rec.recData.Substring(31, 1) == "0")
                    {
                        frontImage = true;
                    }
                    if (rec.recImage.Trim().Length > 0 && frontImage)
                    {
                        frontImage = false;
                        startPos   = System.Convert.ToInt32(rec.recImage.Substring(0, rec.recImage.IndexOf(",")));
                        imgLen     = System.Convert.ToInt32(rec.recImage.Substring(rec.recImage.IndexOf(",") + 1));
                        checkImageBR.BaseStream.Seek(startPos, SeekOrigin.Begin);
                        recB = new byte[imgLen + 1];
                        recB = checkImageBR.ReadBytes(imgLen);
                        Byte2Image(ref cImg, recB, 0);
                        if (frame == 0)
                        {
                            pages = (Bitmap)cImg;

                            //save the first frame
                            pages.Save(outFile, info, ep);
                        }
                        else
                        {
                            //save the intermediate frames
                            ep.Param[0] = new EncoderParameter(enc, System.Convert.ToInt64(EncoderValue.FrameDimensionPage));

                            pages.SaveAdd((Bitmap)cImg, ep);
                        }

                        frame += 1;
                    }
                    reccnt += 1;
                    exporting.pbCleanup.Value = (int)(reccnt / (double)x9Stuff.Count) * 100;
                    Application.DoEvents();
                }
            }
            catch (Exception ex)
            {
                exporting.TopMost = false;
                MessageBox.Show(ex.Message + " rec count=" + reccnt.ToString("###,###,###"), "Error Exporting", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            //flush and close.
            if (pages == null)
            {
                ep.Param[0] = new EncoderParameter(enc, System.Convert.ToInt64(EncoderValue.Flush));
                pages.SaveAdd(ep);
            }
            exporting.Close();
            this.Cursor = Cursors.Default;
        }
Example #30
0
        private void recompress(string input, string output, ImageCodecInfo codecInfo, EncoderValue compressionMethod)
        {
            FileStream        filestream        = new FileStream(input, FileMode.Open, FileAccess.Read);
            Bitmap            bitmap            = new Bitmap(filestream);
            FileStream        filestream2       = new FileStream(output, FileMode.Create, FileAccess.Write);
            EncoderParameter  encoderParameter  = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)compressionMethod);
            EncoderParameters encoderParameters = new EncoderParameters(1);

            encoderParameters.Param[0] = encoderParameter;
            bitmap.Save(filestream2, codecInfo, encoderParameters);
            filestream2.Close();
            progressBar1.BeginInvoke(new MethodInvoker(() => progressBar1.PerformStep()));
        }
Example #31
0
        /// <summary>
        /// This function will join the TIFF file with a specific compression format
        /// </summary>
        /// <param name="imageFiles">array list with source image files</param>
        /// <param name="outFile">target TIFF file to be produced</param>
        /// <param name="compressEncoder">compression codec enum</param>
        public void JoinTiffImages(ArrayList imageFiles, string outFile, EncoderValue compressEncoder)
        {
            try
            {
                //If only one page in the collection, copy it directly to the target file.
                if (imageFiles.Count == 1)
                {
                    File.Copy((string)imageFiles[0], outFile, true);
                    return;
                }

                //use the save encoder
                Encoder enc = Encoder.SaveFlag;

                EncoderParameters ep = new EncoderParameters(2);
                ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
                ep.Param[1] = new EncoderParameter(Encoder.Compression, (long)compressEncoder);

                Bitmap pages = null;
                int frame = 0;
                ImageCodecInfo info = GetEncoderInfo("image/tiff");

                foreach (string strImageFile in imageFiles)
                {
                    if (frame == 0)
                    {
                        pages = (Bitmap)Image.FromFile(strImageFile);

                        //save the first frame
                        pages.Save(outFile, info, ep);
                    }
                    else
                    {
                        //save the intermediate frames
                        ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);

                        Bitmap bm = (Bitmap)Image.FromFile(strImageFile);
                        pages.SaveAdd(bm, ep);
                        bm.Dispose();
                    }

                    if (frame == imageFiles.Count - 1)
                    {
                        //flush and close.
                        ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
                        pages.SaveAdd(ep);
                    }

                    frame++;
                }
            }
            catch (Exception ex)
            {
            #if DEBUG
            Console.WriteLine(ex.Message);
            #endif
                throw;
            }

            return;
        }
Example #32
0
        public static byte[] JoinTiffImages(IEnumerable<string> ImageFilesToJoin, EncoderValue CompressEncoder)
        {
            //holds each of the file data in a byte array
            var FileBytes = new List<byte[]>();

            //we want to pass in each file and it's byte array so we will load each file and pass it into the overload
            foreach (var FileToLoad in ImageFilesToJoin)
            {
                //add the file to load
                FileBytes.Add(File.ReadAllBytes(FileToLoad));
            }

            //now go use the overload
            return JoinTiffImages(FileBytes, CompressEncoder);
        }
Example #33
0
        /// <summary>
        /// Remove a specific page within the image object and save the result to an output image file.
        /// </summary>
        /// <param name="pageNumber">page number to be removed</param>
        /// <param name="compressEncoder">compress encoder after operation</param>
        /// <param name="strFileName">filename to be outputed</param>
        /// <returns></</returns>
        public void RemoveAPage(int pageNumber, EncoderValue compressEncoder, string strFileName)
        {
            try
            {
                //Split the image files to single pages.
                ArrayList arrSplited = SplitTiffImage(this._TempWorkingDir, compressEncoder);

                //Remove the specific page from the collection
                string strPageRemove = string.Format("{0}\\{1}{2}.TIF", _TempWorkingDir, GetFileNameStartString(this._ImageFileName), pageNumber);
                arrSplited.Remove(strPageRemove);

                JoinTiffImages(arrSplited, strFileName, compressEncoder);
            }
            catch (Exception)
            {
                throw;
            }

            return;
        }
Example #34
0
        /// <summary>
        /// Joins the tiff images.
        /// </summary>
        /// <param name="imageFiles">The image files.</param>
        /// <param name="outFile">The out file.</param>
        /// <param name="compressEncoder">The compress encoder.</param>
        public void JoinTiffImages(string[] imageFiles, string outFile, EncoderValue compressEncoder)
        {
            try
            {
                //If only one page in the collection, copy it directly to the target file.
                if (imageFiles.Length == 1)
                {
                    File.Copy(imageFiles[0], outFile, true);
                    return;
                }

                //use the save encoder
                Encoder enc = Encoder.SaveFlag;

                // EncoderParameters ep=new EncoderParameters(2);
                EncoderParameters ep = new EncoderParameters(1);
                ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.MultiFrame);
                //ep.Param[1] = new EncoderParameter(Encoder.Compression,(long)compressEncoder);

                Bitmap         pages = null;
                int            frame = 0;
                ImageCodecInfo info  = GetEncoderInfo("image/tiff");

                foreach (ImageCodecInfo ice in ImageCodecInfo.GetImageDecoders())
                {
                    if (ice.MimeType == "image/tiff")
                    {
                        info = ice;
                    }
                }
                foreach (string strImageFile in imageFiles)
                {
                    if (frame == 0)
                    {
                        pages = (Bitmap)Image.FromFile(strImageFile);

                        //save the first frame
                        pages.Save(outFile, info, ep);
                    }
                    else
                    {
                        //save the intermediate frames
                        ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.FrameDimensionPage);

                        Bitmap bm = (Bitmap)Image.FromFile(strImageFile);
                        pages.SaveAdd(bm, ep);
                        //  bm.Dispose();
                    }

                    if (frame == imageFiles.Length - 1)
                    {
                        //flush and close.
                        ep.Param[0] = new EncoderParameter(enc, (long)EncoderValue.Flush);
                        pages.SaveAdd(ep);
                    }

                    frame++;
                }
                //int gen = GC.GetGeneration(pages);
                //GC.Collect(gen);
            }
            catch (OutOfMemoryException oofmexp)
            {
                ////throw new OutOfMemoryException("An erro has Occured. Please refer to the Event Log");
                MessageBox.Show("please restart the application", "Terrascan T2", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception exp)
            {
                throw new Exception(exp.Message);
            }

            return;
        }
Example #35
0
        /// <summary>
        /// 8bitのグレーの配列からTifを作成して圧縮して保存 (memory byte[] → save 8bit gray .tif)
        /// Save 8bit Tif 
        /// </summary>
        /// <param name="saveFileName">保存ファイル名</param>
        /// <param name="imgGry8">byte(8bit)配列</param>
        /// <param name="imgWidth">画像幅</param>
        /// <param name="imgHeight">画像高さ</param>
        /// <param name="compressionSchemet">圧縮方法</param>
        public static void Save8bitTifFromMemory(string saveFileName, byte[] imgGry8, int imgWidth, int imgHeight, EncoderValue compressionScheme)
        {

            //変換された画像
            using (Bitmap convertedImg = new Bitmap(imgWidth, imgHeight, System.Drawing.Imaging.PixelFormat.Format8bppIndexed))
            {
                //パレット作成
                ColorPalette pal = convertedImg.Palette;

                for (int i = 0; i < 256; ++i)
                {
                    pal.Entries[i] = Color.FromArgb(i, i, i);
                }

                convertedImg.Palette = pal;

                //BitmapDataの作成
                BitmapData bmpdata = null;

                bmpdata = convertedImg.LockBits(new Rectangle(0, 0, imgWidth, imgHeight),
                                        ImageLockMode.WriteOnly,
                                        PixelFormat.Format8bppIndexed);

                //画像の変換とBitmap内への書き込み
                try
                {
                    for (int j = 0; j < imgHeight; ++j)
                    {
                        IntPtr dst_line = (IntPtr)((Int64)bmpdata.Scan0 + j * bmpdata.Stride);
                        Marshal.Copy(imgGry8, j * imgWidth, dst_line, imgWidth);
                    }

                }
                finally
                {
                    if (bmpdata != null)
                    {
                        convertedImg.UnlockBits(bmpdata);
                    }
                }

                if (compressionScheme != EncoderValue.CompressionLZW &&
                        compressionScheme != EncoderValue.CompressionNone &&
                        compressionScheme != EncoderValue.CompressionRle)
                {
                    throw new ArgumentException("compressionScheme");
                }

                //TIFFのImageCodecInfoを取得する
                ImageCodecInfo ici = GetEncoderInfo("image/tiff");
                if (ici == null)
                {
                    return;
                }

                //圧縮方法指定
                EncoderParameters encParam = new EncoderParameters(1);
                encParam.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Compression, (long)compressionScheme);


                //画像保存
                convertedImg.Save(saveFileName, ici, encParam);
            }
        }