static int[][] getDct(string filename) { jpeg_decompress_struct cinfo = new jpeg_decompress_struct(); FileStream objFileStreamHeaderImage = new FileStream(filename, FileMode.Open, FileAccess.Read); cinfo.jpeg_stdio_src(objFileStreamHeaderImage); cinfo.jpeg_read_header(true); var coeffs = cinfo.jpeg_read_coefficients(); const int size = 64; int height = cinfo.Image_height / size; int width = cinfo.Image_width / size; int[][] result = new int[height * width][]; var dct = coeffs[0].Access(0, height); for (int i = 0; i < height * width; i++) { result[i] = new int[size]; } for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { for (int k = 0; k < 64; k++) { result[i * width + j][k] = dct[i][j][k]; } } } return result; }
public void TestMarkerList() { jpeg_decompress_struct cinfo = new jpeg_decompress_struct(); using (FileStream input = new FileStream(Path.Combine(Tester.Testcase, "PARROTS.JPG"), FileMode.Open)) { /* Specify data source for decompression */ cinfo.jpeg_stdio_src(input); const int markerDataLengthLimit = 1000; cinfo.jpeg_save_markers((int)JPEG_MARKER.COM, markerDataLengthLimit); cinfo.jpeg_save_markers((int)JPEG_MARKER.APP0, markerDataLengthLimit); /* Read file header, set default decompression parameters */ cinfo.jpeg_read_header(true); Assert.AreEqual(cinfo.Marker_list.Count, 3); int[] expectedMarkerType = { (int)JPEG_MARKER.APP0, (int)JPEG_MARKER.APP0, (int)JPEG_MARKER.COM }; int[] expectedMarkerOriginalLength = { 14, 3072, 10 }; for (int i = 0; i < cinfo.Marker_list.Count; ++i) { jpeg_marker_struct marker = cinfo.Marker_list[i]; Assert.IsNotNull(marker); Assert.AreEqual(marker.Marker, expectedMarkerType[i]); Assert.AreEqual(marker.OriginalLength, expectedMarkerOriginalLength[i]); Assert.LessOrEqual(marker.Data.Length, markerDataLengthLimit); } } }
private int cur_output_row; /* next row# to write to virtual array */ public bmp_dest_struct(jpeg_decompress_struct cinfo, bool is_os2) { this.cinfo = cinfo; this.is_os2 = is_os2; if (cinfo.Out_color_space == J_COLOR_SPACE.JCS_GRAYSCALE) { m_putGrayRows = true; } else if (cinfo.Out_color_space == J_COLOR_SPACE.JCS_RGB) { if (cinfo.Quantize_colors) m_putGrayRows = true; else m_putGrayRows = false; } else { cinfo.ERREXIT((int)ADDON_MESSAGE_CODE.JERR_BMP_COLORSPACE); } /* Calculate output image dimensions so we can allocate space */ cinfo.jpeg_calc_output_dimensions(); /* Determine width of rows in the BMP file (padded to 4-byte boundary). */ row_width = cinfo.Output_width * cinfo.Output_components; data_width = row_width; while ((row_width & 3) != 0) row_width++; pad_bytes = row_width - data_width; /* Allocate space for inversion array, prepare for write pass */ whole_image = jpeg_common_struct.CreateSamplesArray(row_width, cinfo.Output_height); whole_image.ErrorProcessor = cinfo; cur_output_row = 0; if (cinfo.Progress != null) { cdjpeg_progress_mgr progress = cinfo.Progress as cdjpeg_progress_mgr; if (progress != null) { /* count file input as separate pass */ progress.total_extra_passes++; } } /* Create decompressor output buffer. */ buffer = jpeg_common_struct.AllocJpegSamples(row_width, 1); buffer_height = 1; }
private static void decompress(Stream input, DecompressOptions options, Stream output) { Debug.Assert(input != null); Debug.Assert(options != null); Debug.Assert(output != null); /* Initialize the JPEG decompression object with default error handling. */ jpeg_decompress_struct cinfo = new jpeg_decompress_struct(new cd_jpeg_error_mgr()); /* Insert custom marker processor for COM and APP12. * APP12 is used by some digital camera makers for textual info, * so we provide the ability to display it as text. * If you like, additional APPn marker types can be selected for display, * but don't try to override APP0 or APP14 this way (see libjpeg.doc). */ cinfo.jpeg_set_marker_processor((int)JPEG_MARKER.COM, new jpeg_decompress_struct.jpeg_marker_parser_method(printTextMarker)); cinfo.jpeg_set_marker_processor((int)JPEG_MARKER.APP0 + 12, printTextMarker); /* Specify data source for decompression */ cinfo.jpeg_stdio_src(input); /* Read file header, set default decompression parameters */ cinfo.jpeg_read_header(true); applyOptions(cinfo, options); /* Initialize the output module now to let it override any crucial * option settings (for instance, GIF wants to force color quantization). */ djpeg_dest_struct dest_mgr = null; switch (options.OutputFormat) { case IMAGE_FORMATS.FMT_BMP: dest_mgr = new bmp_dest_struct(cinfo, false); break; case IMAGE_FORMATS.FMT_OS2: dest_mgr = new bmp_dest_struct(cinfo, true); break; default: cinfo.ERREXIT((int)ADDON_MESSAGE_CODE.JERR_UNSUPPORTED_FORMAT); break; } dest_mgr.output_file = output; /* Start decompressor */ cinfo.jpeg_start_decompress(); /* Write output file header */ dest_mgr.start_output(); /* Process data */ while (cinfo.Output_scanline < cinfo.Output_height) { int num_scanlines = cinfo.jpeg_read_scanlines(dest_mgr.buffer, dest_mgr.buffer_height); dest_mgr.put_pixel_rows(num_scanlines); } /* Finish decompression and release memory. * I must do it in this order because output module has allocated memory * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory. */ dest_mgr.finish_output(); cinfo.jpeg_finish_decompress(); /* All done. */ if (cinfo.Err.Num_warnings != 0) Console.WriteLine("Corrupt-data warning count is not zero"); }
static void applyOptions(jpeg_decompress_struct decompressor, DecompressOptions options) { Debug.Assert(decompressor != null); Debug.Assert(options != null); if (options.QuantizeColors) { decompressor.Quantize_colors = true; decompressor.Desired_number_of_colors = options.DesiredNumberOfColors; } decompressor.Dct_method = options.DCTMethod; decompressor.Dither_mode = options.DitherMode; if (options.Debug) decompressor.Err.Trace_level = 1; if (options.Fast) { /* Select recommended processing options for quick-and-dirty output. */ decompressor.Two_pass_quantize = false; decompressor.Dither_mode = J_DITHER_MODE.JDITHER_ORDERED; if (!decompressor.Quantize_colors) /* don't override an earlier -colors */ decompressor.Desired_number_of_colors = 216; decompressor.Dct_method = JpegConstants.JDCT_FASTEST; decompressor.Do_fancy_upsampling = false; } if (options.Grayscale) decompressor.Out_color_space = J_COLOR_SPACE.JCS_GRAYSCALE; if (options.NoSmooth) decompressor.Do_fancy_upsampling = false; if (options.OnePass) decompressor.Two_pass_quantize = false; if (options.Scaled) { decompressor.Scale_num = options.ScaleNumerator; decompressor.Scale_denom = options.ScaleDenominator; } }
/// <summary> /// This is the default resync_to_restart method for data source /// managers to use if they don't have any better approach. /// </summary> /// <param name="cinfo">An instance of <see cref="jpeg_decompress_struct"/></param> /// <param name="desired">The desired</param> /// <returns><c>false</c> if suspension is required.</returns> /// <remarks>That method assumes that no backtracking is possible. /// Some data source managers may be able to back up, or may have /// additional knowledge about the data which permits a more /// intelligent recovery strategy; such managers would /// presumably supply their own resync method.<br/><br/> /// read_restart_marker calls resync_to_restart if it finds a marker other than /// the restart marker it was expecting. (This code is *not* used unless /// a nonzero restart interval has been declared.) cinfo.unread_marker is /// the marker code actually found (might be anything, except 0 or FF). /// The desired restart marker number (0..7) is passed as a parameter.<br/><br/> /// This routine is supposed to apply whatever error recovery strategy seems /// appropriate in order to position the input stream to the next data segment. /// Note that cinfo.unread_marker is treated as a marker appearing before /// the current data-source input point; usually it should be reset to zero /// before returning.<br/><br/> /// This implementation is substantially constrained by wanting to treat the /// input as a data stream; this means we can't back up. Therefore, we have /// only the following actions to work with:<br/> /// 1. Simply discard the marker and let the entropy decoder resume at next /// byte of file.<br/> /// 2. Read forward until we find another marker, discarding intervening /// data. (In theory we could look ahead within the current bufferload, /// without having to discard data if we don't find the desired marker. /// This idea is not implemented here, in part because it makes behavior /// dependent on buffer size and chance buffer-boundary positions.)<br/> /// 3. Leave the marker unread (by failing to zero cinfo.unread_marker). /// This will cause the entropy decoder to process an empty data segment, /// inserting dummy zeroes, and then we will reprocess the marker.<br/> /// #2 is appropriate if we think the desired marker lies ahead, while #3 is /// appropriate if the found marker is a future restart marker (indicating /// that we have missed the desired restart marker, probably because it got /// corrupted).<br/> /// We apply #2 or #3 if the found marker is a restart marker no more than /// two counts behind or ahead of the expected one. We also apply #2 if the /// found marker is not a legal JPEG marker code (it's certainly bogus data). /// If the found marker is a restart marker more than 2 counts away, we do #1 /// (too much risk that the marker is erroneous; with luck we will be able to /// resync at some future point).<br/> /// For any valid non-restart JPEG marker, we apply #3. This keeps us from /// overrunning the end of a scan. An implementation limited to single-scan /// files might find it better to apply #2 for markers other than EOI, since /// any other marker would have to be bogus data in that case.</remarks> public override bool resync_to_restart(jpeg_decompress_struct cinfo, int desired) { Tiff tif = m_sp.GetTiff(); Tiff.ErrorExt(tif, tif.m_clientdata, "LibJpeg", "Unexpected error"); return false; }
/// <summary> /// This is the default resync_to_restart method for data source /// managers to use if they don't have any better approach. /// </summary> /// <param name="cinfo">An instance of <see cref="jpeg_decompress_struct"/></param> /// <param name="desired">The desired</param> /// <returns><c>false</c> if suspension is required.</returns> /// <remarks>That method assumes that no backtracking is possible. /// Some data source managers may be able to back up, or may have /// additional knowledge about the data which permits a more /// intelligent recovery strategy; such managers would /// presumably supply their own resync method.<br/><br/> /// /// read_restart_marker calls resync_to_restart if it finds a marker other than /// the restart marker it was expecting. (This code is *not* used unless /// a nonzero restart interval has been declared.) cinfo.unread_marker is /// the marker code actually found (might be anything, except 0 or FF). /// The desired restart marker number (0..7) is passed as a parameter.<br/><br/> /// /// This routine is supposed to apply whatever error recovery strategy seems /// appropriate in order to position the input stream to the next data segment. /// Note that cinfo.unread_marker is treated as a marker appearing before /// the current data-source input point; usually it should be reset to zero /// before returning.<br/><br/> /// /// This implementation is substantially constrained by wanting to treat the /// input as a data stream; this means we can't back up. Therefore, we have /// only the following actions to work with:<br/> /// 1. Simply discard the marker and let the entropy decoder resume at next /// byte of file.<br/> /// 2. Read forward until we find another marker, discarding intervening /// data. (In theory we could look ahead within the current bufferload, /// without having to discard data if we don't find the desired marker. /// This idea is not implemented here, in part because it makes behavior /// dependent on buffer size and chance buffer-boundary positions.)<br/> /// 3. Leave the marker unread (by failing to zero cinfo.unread_marker). /// This will cause the entropy decoder to process an empty data segment, /// inserting dummy zeroes, and then we will reprocess the marker.<br/> /// /// #2 is appropriate if we think the desired marker lies ahead, while #3 is /// appropriate if the found marker is a future restart marker (indicating /// that we have missed the desired restart marker, probably because it got /// corrupted).<br/> /// We apply #2 or #3 if the found marker is a restart marker no more than /// two counts behind or ahead of the expected one. We also apply #2 if the /// found marker is not a legal JPEG marker code (it's certainly bogus data). /// If the found marker is a restart marker more than 2 counts away, we do #1 /// (too much risk that the marker is erroneous; with luck we will be able to /// resync at some future point).<br/> /// For any valid non-restart JPEG marker, we apply #3. This keeps us from /// overrunning the end of a scan. An implementation limited to single-scan /// files might find it better to apply #2 for markers other than EOI, since /// any other marker would have to be bogus data in that case.</remarks> public virtual bool resync_to_restart(jpeg_decompress_struct cinfo, int desired) { /* Always put up a warning. */ cinfo.WARNMS(J_MESSAGE_CODE.JWRN_MUST_RESYNC, cinfo.m_unread_marker, desired); /* Outer loop handles repeated decision after scanning forward. */ int action = 1; for ( ; ; ) { if (cinfo.m_unread_marker < (int)JPEG_MARKER.SOF0) { /* invalid marker */ action = 2; } else if (cinfo.m_unread_marker < (int)JPEG_MARKER.RST0 || cinfo.m_unread_marker > (int)JPEG_MARKER.RST7) { /* valid non-restart marker */ action = 3; } else { if (cinfo.m_unread_marker == ((int)JPEG_MARKER.RST0 + ((desired + 1) & 7)) || cinfo.m_unread_marker == ((int)JPEG_MARKER.RST0 + ((desired + 2) & 7))) { /* one of the next two expected restarts */ action = 3; } else if (cinfo.m_unread_marker == ((int)JPEG_MARKER.RST0 + ((desired - 1) & 7)) || cinfo.m_unread_marker == ((int)JPEG_MARKER.RST0 + ((desired - 2) & 7))) { /* a prior restart, so advance */ action = 2; } else { /* desired restart or too far away */ action = 1; } } cinfo.TRACEMS(4, J_MESSAGE_CODE.JTRC_RECOVERY_ACTION, cinfo.m_unread_marker, action); switch (action) { case 1: /* Discard marker and let entropy decoder resume processing. */ cinfo.m_unread_marker = 0; return true; case 2: /* Scan to the next marker, and repeat the decision loop. */ if (!cinfo.m_marker.next_marker()) return false; break; case 3: /* Return without advancing past this marker. */ /* Entropy decoder will be forced to process an empty segment. */ return true; } } }
private void cleanState() { m_compression = null; m_decompression = null; m_common = null; m_h_sampling = 0; m_v_sampling = 0; m_jpegtables = null; m_jpegtables_length = 0; m_jpegquality = 0; m_jpegcolormode = 0; m_jpegtablesmode = 0; m_ycbcrsampling_fetched = false; m_recvparams = 0; m_subaddress = null; m_recvtime = 0; m_faxdcs = null; m_rawDecode = false; m_rawEncode = false; m_cinfo_initialized = false; m_err = null; m_photometric = 0; m_bytesperline = 0; m_ds_buffer = new byte[JpegConstants.MAX_COMPONENTS][][]; m_scancount = 0; m_samplesperclump = 0; }
public static jvirt_array<BitMiracle.LibJpeg.Classic.JBLOCK>[] ReadCoefFromImage(string fullPath) { var img = new Bitmap(fullPath); var width = img.Width; var height = img.Height; img.Dispose(); BitMiracle.LibJpeg.Classic.jpeg_decompress_struct oJpegDecompress = new BitMiracle.LibJpeg.Classic.jpeg_decompress_struct(); System.IO.FileStream oFileStreamImage = new System.IO.FileStream(fullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read); oJpegDecompress.jpeg_stdio_src(oFileStreamImage); oJpegDecompress.jpeg_read_header(true); BitMiracle.LibJpeg.Classic.jvirt_array<BitMiracle.LibJpeg.Classic.JBLOCK>[] JBlock = oJpegDecompress.jpeg_read_coefficients(); oJpegDecompress.jpeg_finish_decompress(); oFileStreamImage.Close(); return JBlock; }
private bool jpeg_create_decompress_encap() { try { m_libjpeg_jpeg_decompress_struct = new jpeg_decompress_struct(m_libjpeg_jpeg_error_mgr); } catch (Exception) { return false; } return true; }
private void cleanState() { m_jpeg_interchange_format = 0; m_jpeg_interchange_format_length = 0; m_jpeg_proc = 0; m_subsamplingcorrect_done = false; m_subsampling_tag = false; m_subsampling_hor = 0; m_subsampling_ver = 0; m_qtable_offset_count = 0; m_dctable_offset_count = 0; m_actable_offset_count = 0; m_qtable_offset = new uint[3]; m_dctable_offset = new uint[3]; m_actable_offset = new uint[3]; m_restart_interval = 0; m_libjpeg_jpeg_decompress_struct = null; m_file_size = 0; m_image_width = 0; m_image_length = 0; m_strile_width = 0; m_strile_length = 0; m_strile_length_total = 0; m_samples_per_pixel = 0; m_plane_sample_offset = 0; m_samples_per_pixel_per_plane = 0; m_subsamplingcorrect = false; m_subsampling_force_desubsampling_inside_decompression = false; m_qtable = new byte[4][]; m_dctable = new byte[4][]; m_actable = new byte[4][]; m_restart_index = 0; m_sof_log = false; m_sof_marker_id = 0; m_sof_x = 0; m_sof_y = 0; m_sof_c = new byte[3]; m_sof_hv = new byte[3]; m_sof_tq = new byte[3]; m_sos_cs = new byte[3]; m_sos_tda = new byte[3]; m_sos_end = new SosEnd[3]; m_readheader_done = false; m_writeheader_done = false; m_write_cursample = 0; m_write_curstrile = 0; m_libjpeg_session_active = false; m_libjpeg_jpeg_query_style = 0; m_libjpeg_jpeg_error_mgr = null; m_libjpeg_jpeg_source_mgr = null; m_subsampling_convert_log = false; m_subsampling_convert_ylinelen = 0; m_subsampling_convert_ylines = 0; m_subsampling_convert_clinelen = 0; m_subsampling_convert_clines = 0; m_subsampling_convert_ybuf = null; m_subsampling_convert_cbbuf = null; m_subsampling_convert_crbuf = null; m_subsampling_convert_ycbcrimage = null; m_subsampling_convert_clinelenout = 0; m_subsampling_convert_state = 0; m_bytes_per_line = 0; m_lines_per_strile = 0; m_in_buffer_source = OJPEGStateInBufferSource.osibsNotSetYet; m_in_buffer_next_strile = 0; m_in_buffer_strile_count = 0; m_in_buffer_file_pos = 0; m_in_buffer_file_pos_log = false; m_in_buffer_file_togo = 0; m_in_buffer_togo = 0; m_in_buffer_cur = 0; // index into m_in_buffer m_in_buffer = new byte[OJPEG_BUFFER]; m_out_state = 0; m_out_buffer = new byte[OJPEG_BUFFER]; m_skip_buffer = null; m_forceProcessedRgbOutput = false; }
static string outfilename; /* for -outfile switch */ public static void Main(string[] args) { progname = Path.GetFileName(Environment.GetCommandLineArgs()[0]); /* Initialize the JPEG decompression object with default error handling. */ cd_jpeg_error_mgr err = new cd_jpeg_error_mgr(); jpeg_decompress_struct cinfo = new jpeg_decompress_struct(err); /* Insert custom marker processor for COM and APP12. * APP12 is used by some digital camera makers for textual info, * so we provide the ability to display it as text. * If you like, additional APPn marker types can be selected for display, * but don't try to override APP0 or APP14 this way (see libjpeg.doc). */ cinfo.jpeg_set_marker_processor((int)JPEG_MARKER.COM, new jpeg_decompress_struct.jpeg_marker_parser_method(print_text_marker)); cinfo.jpeg_set_marker_processor((int)JPEG_MARKER.APP0 + 12, print_text_marker); /* Scan command line to find file names. */ /* It is convenient to use just one switch-parsing routine, but the switch * values read here are ignored; we will rescan the switches after opening * the input file. * (Exception: tracing level set here controls verbosity for COM markers * found during jpeg_read_header...) */ int file_index; if (!parse_switches(cinfo, args, false, out file_index)) { usage(); return; } /* Must have either -outfile switch or explicit output file name */ if (outfilename == null) { // file_index should point to input file if (file_index != args.Length - 2) { Console.WriteLine(string.Format("{0}: must name one input and one output file.", progname)); usage(); return; } // output file comes right after input one outfilename = args[file_index + 1]; } else { // file_index should point to input file if (file_index != args.Length - 1) { Console.WriteLine(string.Format("{0}: must name one input and one output file.", progname)); usage(); return; } } /* Open the input file. */ FileStream input_file = null; if (file_index < args.Length) { try { input_file = new FileStream(args[file_index], FileMode.Open); } catch (Exception e) { Console.WriteLine(string.Format("{0}: can't open {1}", progname, args[file_index])); Console.WriteLine(e.Message); return; } } else { Console.WriteLine(string.Format("{0}: sorry, can't read file from console")); return; } /* Open the output file. */ FileStream output_file = null; if (outfilename != null) { try { output_file = new FileStream(outfilename, FileMode.Create); } catch (Exception e) { Console.WriteLine(string.Format("{0}: can't open {1}", progname, args[file_index])); Console.WriteLine(e.Message); return; } } else { Console.WriteLine(string.Format("{0}: sorry, can't write file to console")); return; } /* Specify data source for decompression */ cinfo.jpeg_stdio_src(input_file); /* Read file header, set default decompression parameters */ cinfo.jpeg_read_header(true); /* Adjust default decompression parameters by re-parsing the options */ parse_switches(cinfo, args, true, out file_index); /* Initialize the output module now to let it override any crucial * option settings (for instance, GIF wants to force color quantization). */ djpeg_dest_struct dest_mgr = null; switch (requested_fmt) { case IMAGE_FORMATS.FMT_BMP: dest_mgr = new bmp_dest_struct(cinfo, false); break; case IMAGE_FORMATS.FMT_OS2: dest_mgr = new bmp_dest_struct(cinfo, true); break; default: cinfo.ERREXIT((int)ADDON_MESSAGE_CODE.JERR_UNSUPPORTED_FORMAT); break; } dest_mgr.output_file = output_file; /* Start decompressor */ cinfo.jpeg_start_decompress(); /* Write output file header */ dest_mgr.start_output(); /* Process data */ while (cinfo.Output_scanline < cinfo.Output_height) { int num_scanlines = cinfo.jpeg_read_scanlines(dest_mgr.buffer, dest_mgr.buffer_height); dest_mgr.put_pixel_rows(num_scanlines); } /* Finish decompression and release memory. * I must do it in this order because output module has allocated memory * of lifespan JPOOL_IMAGE; it needs to finish before releasing memory. */ dest_mgr.finish_output(); cinfo.jpeg_finish_decompress(); /* Close files, if we opened them */ input_file.Close(); input_file.Dispose(); output_file.Close(); output_file.Dispose(); /* All done. */ if (cinfo.Err.Num_warnings != 0) Console.WriteLine("Corrupt-data warning count is not zero"); }
/// <summary> /// Parse optional switches. /// Returns argv[] index of first file-name argument (== argc if none). /// Any file names with indexes <= last_file_arg_seen are ignored; /// they have presumably been processed in a previous iteration. /// (Pass 0 for last_file_arg_seen on the first or only iteration.) /// for_real is false on the first (dummy) pass; we may skip any expensive /// processing. /// </summary> static bool parse_switches(jpeg_decompress_struct cinfo, string[] argv, bool for_real, out int last_file_arg_seen) { string arg; /* Set up default JPEG parameters. */ requested_fmt = IMAGE_FORMATS.FMT_BMP; /* set default output file format */ outfilename = null; last_file_arg_seen = -1; cinfo.Err.Trace_level = 0; /* Scan command line options, adjust parameters */ int argn = 0; for ( ; argn < argv.Length; argn++) { arg = argv[argn]; if (arg[0] != '-') { /* Not a switch, must be a file name argument */ last_file_arg_seen = argn; break; } arg = arg.Substring(1); if (cdjpeg_utils.keymatch(arg, "bmp", 1)) { /* BMP output format. */ requested_fmt = IMAGE_FORMATS.FMT_BMP; } else if (cdjpeg_utils.keymatch(arg, "colors", 1) || cdjpeg_utils.keymatch(arg, "colours", 1) || cdjpeg_utils.keymatch(arg, "quantize", 1) || cdjpeg_utils.keymatch(arg, "quantise", 1)) { /* Do color quantization. */ if (++argn >= argv.Length) /* advance to next argument */ return false; try { int val = int.Parse(argv[argn]); cinfo.Desired_number_of_colors = val; cinfo.Quantize_colors = true; } catch (Exception e) { Console.WriteLine(e.Message); return false; } } else if (cdjpeg_utils.keymatch(arg, "dct", 2)) { /* Select IDCT algorithm. */ if (++argn >= argv.Length) /* advance to next argument */ return false; if (cdjpeg_utils.keymatch(argv[argn], "int", 1)) cinfo.Dct_method = J_DCT_METHOD.JDCT_ISLOW; else if (cdjpeg_utils.keymatch(argv[argn], "fast", 2)) cinfo.Dct_method = J_DCT_METHOD.JDCT_IFAST; else if (cdjpeg_utils.keymatch(argv[argn], "float", 2)) cinfo.Dct_method = J_DCT_METHOD.JDCT_FLOAT; else return false; } else if (cdjpeg_utils.keymatch(arg, "dither", 2)) { /* Select dithering algorithm. */ if (++argn >= argv.Length) /* advance to next argument */ return false; if (cdjpeg_utils.keymatch(argv[argn], "fs", 2)) cinfo.Dither_mode = J_DITHER_MODE.JDITHER_FS; else if (cdjpeg_utils.keymatch(argv[argn], "none", 2)) cinfo.Dither_mode = J_DITHER_MODE.JDITHER_NONE; else if (cdjpeg_utils.keymatch(argv[argn], "ordered", 2)) cinfo.Dither_mode = J_DITHER_MODE.JDITHER_ORDERED; else return false; } else if (cdjpeg_utils.keymatch(arg, "debug", 1) || cdjpeg_utils.keymatch(arg, "verbose", 1)) { /* Enable debug printouts. */ /* On first -d, print version identification */ if (!printed_version) { Console.Write(string.Format("Bit Miracle's DJPEG, version {0}\n{1}\n", jpeg_common_struct.Version, jpeg_common_struct.Copyright)); printed_version = true; } cinfo.Err.Trace_level++; } else if (cdjpeg_utils.keymatch(arg, "fast", 1)) { /* Select recommended processing options for quick-and-dirty output. */ cinfo.Two_pass_quantize = false; cinfo.Dither_mode = J_DITHER_MODE.JDITHER_ORDERED; if (!cinfo.Quantize_colors) /* don't override an earlier -colors */ cinfo.Desired_number_of_colors = 216; cinfo.Dct_method = JpegConstants.JDCT_FASTEST; cinfo.Do_fancy_upsampling = false; } else if (cdjpeg_utils.keymatch(arg, "grayscale", 2) || cdjpeg_utils.keymatch(arg, "greyscale", 2)) { /* Force monochrome output. */ cinfo.Out_color_space = J_COLOR_SPACE.JCS_GRAYSCALE; } else if (cdjpeg_utils.keymatch(arg, "nosmooth", 3)) { /* Suppress fancy upsampling */ cinfo.Do_fancy_upsampling = false; } else if (cdjpeg_utils.keymatch(arg, "onepass", 3)) { /* Use fast one-pass quantization. */ cinfo.Two_pass_quantize = false; } else if (cdjpeg_utils.keymatch(arg, "os2", 3)) { /* BMP output format (OS/2 flavor). */ requested_fmt = IMAGE_FORMATS.FMT_OS2; } else if (cdjpeg_utils.keymatch(arg, "outfile", 4)) { /* Set output file name. */ if (++argn >= argv.Length) /* advance to next argument */ return false; outfilename = argv[argn]; /* save it away for later use */ } else if (cdjpeg_utils.keymatch(arg, "scale", 1)) { /* Scale the output image by a fraction M/N. */ if (++argn >= argv.Length) /* advance to next argument */ return false; int slashPos = argv[argn].IndexOf('/'); if (slashPos == -1) return false; try { string num = argv[argn].Substring(0, slashPos); cinfo.Scale_num = int.Parse(num); string denom = argv[argn].Substring(slashPos + 1); cinfo.Scale_denom = int.Parse(denom); } catch (Exception e) { Console.WriteLine(e.Message); return false; } } else /* bogus switch */ return false; } return true; }
/// <summary> /// Marker processor for COM and interesting APPn markers. /// This replaces the library's built-in processor, which just skips the marker. /// We want to print out the marker as text, to the extent possible. /// Note this code relies on a non-suspending data source. /// </summary> static bool printTextMarker(jpeg_decompress_struct cinfo) { bool traceit = (cinfo.Err.Trace_level >= 1); int length = jpeg_getc(cinfo) << 8; length += jpeg_getc(cinfo); length -= 2; /* discount the length word itself */ if (traceit) { if (cinfo.Unread_marker == (int)JPEG_MARKER.COM) { Console.WriteLine("Comment, length {0}:", length); } else { /* assume it is an APPn otherwise */ Console.WriteLine("APP{0}, length {1}:", cinfo.Unread_marker - JPEG_MARKER.APP0, length); } } int lastch = 0; while (--length >= 0) { int ch = jpeg_getc(cinfo); if (traceit) { /* Emit the character in a readable form. * Nonprintables are converted to \nnn form, * while \ is converted to \\. * Newlines in CR, CR/LF, or LF form will be printed as one newline. */ if (ch == '\r') { Console.WriteLine(); } else if (ch == '\n') { if (lastch != '\r') Console.WriteLine(); } else if (ch == '\\') { Console.Write("\\\\"); } else if (!Char.IsControl((char)ch)) { Console.Write(ch); } else { Console.Write(encodeOctalString(ch)); } lastch = ch; } } if (traceit) Console.WriteLine(); return true; }
private bool TIFFjpeg_create_decompress() { /* initialize JPEG error handling */ try { m_decompression = new jpeg_decompress_struct(new JpegErrorManager(this)); m_common = m_decompression; } catch (Exception) { return false; } return true; }
/// <summary> /// Read next byte /// </summary> static int jpeg_getc(jpeg_decompress_struct decompressor) { int v; if (!decompressor.Src.GetByte(out v)) decompressor.ERREXIT(J_MESSAGE_CODE.JERR_CANT_SUSPEND); return v; }
public static string IncImageDCT(string fullPath) { string suffix = "testDCT"; var img = new Bitmap(fullPath); var width = img.Width; var height = img.Height; int hd = height / 8; int wd = width / 8; img.Dispose(); BitMiracle.LibJpeg.Classic.jpeg_decompress_struct oJpegDecompress = new BitMiracle.LibJpeg.Classic.jpeg_decompress_struct(); System.IO.FileStream oFileStreamImage = new System.IO.FileStream(fullPath, System.IO.FileMode.Open, System.IO.FileAccess.Read); oJpegDecompress.jpeg_stdio_src(oFileStreamImage); oJpegDecompress.jpeg_read_header(true); BitMiracle.LibJpeg.Classic.jvirt_array<BitMiracle.LibJpeg.Classic.JBLOCK>[] JBlock = oJpegDecompress.jpeg_read_coefficients(); var block = JBlock[0].Access(0, hd); // accessing the element for (int i = 0; i < hd; i++) { for (int j = 0; j < wd; j++) { short t = block[i][j].data[0]; if ((t >= 0 && t % 2 == 1) || (t < 0 && t % 2 == 0)) { t--; } else if ((t >= 0 && t % 2 == 0) || (t < 0 && t % 2 == 1)) { t++; } block[i][j].data[0] = t; } } oJpegDecompress.jpeg_finish_decompress(); oFileStreamImage.Close(); //// string filenameNew = MyHelper.AppendFileName(fullPath, suffix); System.IO.FileStream objFileStreamMegaMap = System.IO.File.Create(filenameNew); BitMiracle.LibJpeg.Classic.jpeg_compress_struct oJpegCompress = new BitMiracle.LibJpeg.Classic.jpeg_compress_struct(); oJpegCompress.jpeg_stdio_dest(objFileStreamMegaMap); oJpegDecompress.jpeg_copy_critical_parameters(oJpegCompress); oJpegCompress.Image_height = height; oJpegCompress.Image_width = width; oJpegCompress.jpeg_write_coefficients(JBlock); oJpegCompress.jpeg_finish_compress(); objFileStreamMegaMap.Close(); oJpegDecompress.jpeg_abort_decompress(); return filenameNew; }