private void SaveImage() { Leadtools.RasterImageFormat rif; switch (strImgFormat) { case "jpg": rif = Leadtools.RasterImageFormat.Jpeg; rasterCodecs.Options.Jpeg.Save.QualityFactor = intImgQuality * 255 / 100; rasterCodecs.Options.Jpeg.Save.QualityFactor = Math.Min(rasterCodecs.Options.Jpeg.Save.QualityFactor, 255); rasterCodecs.Options.Jpeg.Save.QualityFactor = Math.Max(rasterCodecs.Options.Jpeg.Save.QualityFactor, 2); rasterCodecs.Save(img, strTargetImage, rif, 24); break; case "gif": rif = Leadtools.RasterImageFormat.Gif; rasterCodecs.Save(img, strTargetImage, rif, img.BitsPerPixel, 1, img.PageCount, 1, CodecsSavePageMode.Overwrite); break; case "png": rif = Leadtools.RasterImageFormat.Png; rasterCodecs.Save(img, strTargetImage, rif, img.BitsPerPixel); break; } }
//public static byte[] CreateBarcode( string value, int resolution, int Width, int Height, bool Save2File,bool usingMemory, ref string ErrMsg) //{ // byte[] arrImg; // BarcodeEngine barEngine; // try // { // RasterImage theImage = RasterImage.Create((int)(8.5 * resolution), (int)(11.0 * resolution), 1, resolution, RasterColor.FromKnownColor(RasterKnownColor.White)); // // Unlock barcode support. // // Note that this is a sample key, which will not work in your toolkit // BarcodeEngine.Startup(BarcodeMajorTypeFlags.Barcodes1d); // BarcodeEngine.Startup(BarcodeMajorTypeFlags.BarcodesPdfWrite); // BarcodeEngine.Startup(BarcodeMajorTypeFlags.BarcodesDatamatrixWrite); // BarcodeEngine.Startup(BarcodeMajorTypeFlags.BarcodesQrWrite); // // Initialize barcodes // barEngine = new BarcodeEngine(); // BarcodeData data = new BarcodeData(); // LeadRect rc = new LeadRect(0, 0, Width, Height); // data.Unit = BarcodeUnit.ScanlinesPerPixels; // data.Location = rc; // data.SearchType = BarcodeSearchTypeFlags.DatamatrixDefault; // string[] barcodeText; // barcodeText = new string[1]; // barcodeText[0] = value; // data.Data = BarcodeData.ConvertFromStringArray(barcodeText); // BarcodeColor barColor = new BarcodeColor(); // barColor.BarColor = RasterColor.FromKnownColor(RasterKnownColor.Black); // barColor.SpaceColor = RasterColor.FromKnownColor(RasterKnownColor.White); // Barcode1d bar1d = new Barcode1d(); // BarcodeWritePdf barPDF = new BarcodeWritePdf(); // BarcodeWriteDatamatrix barDM = new BarcodeWriteDatamatrix(); // bar1d.StandardFlags = Barcode1dStandardFlags.Barcode1dCode128EncodeA; // barDM.Justify = BarcodeJustifyFlags.Right; // barDM.FileIdHigh = 0; // barDM.FileIdLow = 0; // barDM.GroupNumber = 0; // barDM.GroupTotal = 0; // barDM.XModule = 0; // BarcodeWriteQr barQR = new BarcodeWriteQr(); // string barcodeFileName = AppDomain.CurrentDomain.BaseDirectory + @"\barcode.tif"; // barEngine.Write(theImage, data, barColor, BarcodeWriteFlags.UseColors | BarcodeWriteFlags.Transparent | BarcodeWriteFlags.DisableCompression, bar1d, barPDF, barDM, barQR, LeadRect.Empty); // if (usingMemory) // { // using (MemoryStream _stream = new MemoryStream()) // { // using (RasterCodecs _Codecs = new RasterCodecs()) // { // _Codecs.Save(theImage, _stream, RasterImageFormat.Tif, theImage.BitsPerPixel); // arrImg = _stream.ToArray(); // if (Save2File) // { // _Codecs.Save(theImage, barcodeFileName, RasterImageFormat.Tif, theImage.BitsPerPixel); // } // } // } // } // else // { // using (RasterCodecs _Codecs = new RasterCodecs()) // { // _Codecs.Save(theImage, barcodeFileName, RasterImageFormat.Tif, theImage.BitsPerPixel); // arrImg = System.IO.File.ReadAllBytes(barcodeFileName); // } // } // } // catch (Exception ex) // { // ErrMsg = ex.Message; // return null; // } // return arrImg; //} public static byte[] CreateBarcode(BarcodeSymbology _BarcodeSymbology, string value, int resolution, int Width, int Height, bool Save2File, bool usingMemory, ref string ErrMsg) { ErrMsg = ""; BarcodeEngine barcodeEngineInstance = new BarcodeEngine(); RasterImage theImage = RasterImage.Create((int)(8.5 * resolution), (int)(11.0 * resolution), 1, resolution, RasterColor.FromKnownColor(RasterKnownColor.White)); // Create a UPC A barcode BarcodeData data = new BarcodeData(); data.Symbology = _BarcodeSymbology; data.Value = value; data.Bounds = new LogicalRectangle(10, 10, Width, Height, LogicalUnit.Pixel); // Setup the options to enable error checking and show the text on the bottom of the barcode OneDBarcodeWriteOptions options = new OneDBarcodeWriteOptions(); options.EnableErrorCheck = true; options.TextPosition = BarcodeOutputTextPosition.None;// OneDBarcodeTextPosition.Default; byte[] arrImg; try { string barcodeFileName = AppDomain.CurrentDomain.BaseDirectory + @"\barcode.tif"; // Write the barcode barcodeEngineInstance.Writer.WriteBarcode(theImage, data, options); if (usingMemory) { using (MemoryStream _stream = new MemoryStream()) { using (RasterCodecs _Codecs = new RasterCodecs()) { _Codecs.Save(theImage, _stream, RasterImageFormat.Tif, theImage.BitsPerPixel); arrImg = _stream.ToArray(); if (Save2File) { _Codecs.Save(theImage, barcodeFileName, RasterImageFormat.Tif, theImage.BitsPerPixel); } } } } else { using (RasterCodecs _Codecs = new RasterCodecs()) { _Codecs.Save(theImage, barcodeFileName, RasterImageFormat.Tif, theImage.BitsPerPixel); arrImg = System.IO.File.ReadAllBytes(barcodeFileName); } } } catch (Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); ErrMsg = ex.Message; return(null); } return(arrImg); }
public byte[] GetImageBytes() { using (var stream = new MemoryStream()) { codec.Save(ImageData, stream, RasterImageFormat.CcittGroup4, 0, 1, TotalPages, 1, CodecsSavePageMode.Overwrite); foreach (var entry in tagsByPageNumber) { codec.WriteTag(stream, entry.Key, entry.Value); } return(stream.GetBuffer()); } }
public static void MergeFiles(string mainFile, string appendFile, bool annotation) { if (MergeFilesByCopy(mainFile, appendFile)) { return; } RasterCodecs codec = new RasterCodecs(); RasterImage image = null; RasterTagMetadata[] tagsData = null; // stores the annotatin RasterImage image2 = null; try { // load the image and annotation information for the // append file. image = codec.Load(appendFile); int pageCount = image.PageCount; if (annotation) { tagsData = new RasterTagMetadata[pageCount]; for (int i = 0; i < pageCount; ++i) { tagsData[i] = codec.ReadTag(appendFile, i + 1, RasterTagMetadata.AnnotationTiff); } } StatusForm statusForm = new StatusForm(); statusForm.LoadFormData(appendFile, mainFile, pageCount); statusForm.Show(); statusForm.Refresh(); image2 = codec.Load(mainFile); int mainPageNumber = image2.PageCount; for (int i = 0; i < pageCount; ++i) { codec.Save(image, mainFile, RasterImageFormat.CcittGroup4, 1, i + 1, i + 1, 1, CodecsSavePageMode.Append); if (annotation) { if ((tagsData != null) && (tagsData[i] != null)) { codec.WriteTag(mainFile, mainPageNumber + i + 1, tagsData[i]); } } statusForm.ShowPageInfo(i); } statusForm.Close(); } finally { if (image != null) { image.Dispose(); } if (image2 != null) { image2.Dispose(); } } }
public async void AddBackImage(ContactModel contactItem, RasterImage backImage, Stream imageStream) { string imageFileName = Path.GetFileNameWithoutExtension(contactItem.Picture).Replace("image_", ""); string backImagePath = Path.Combine(HomePage.APP_DIR, $"back_{imageFileName}.jpeg"); if (imageStream != null) { await DependencyService.Get <IPictureSaver>().SaveImage(imageStream, backImagePath, PictureSaveResolution.Medium, false); } else if (backImage != null) { LeadSize size = ImageSizeHelper.GetImageSize(backImage.Width, backImage.Height, PictureSaveResolution.Medium); ResizeInterpolateCommand resizeInterpolateCommand = new ResizeInterpolateCommand(size.Width, size.Height, ResizeInterpolateCommandType.Resample); resizeInterpolateCommand.Run(backImage); using (var codecs = new RasterCodecs()) { codecs.Save(backImage, backImagePath, RasterImageFormat.Jpeg, 0); } } contactItem.BackImage = backImagePath; HomePage.Instance.SaveContactList(); SetBackImage(); }
//fully qualified path & filename public LT_DPI_Converter(string srcFileName, string destFileName) { RasterCodecs codecs = new RasterCodecs(); System.IO.File.Copy(srcFileName, destFileName, true); //Read Original Values RasterImage oldimage = codecs.Load(srcFileName); //Change values and save a new file name RasterImage newimage = codecs.Load(destFileName); int newResolution = 300; //BR says all files need to be 300 DPI. This should probably be an enum. // Load the source image from disk newimage.XResolution = newResolution; newimage.YResolution = newResolution; SizeCommand command = new SizeCommand(); command.Width = oldimage.Width; command.Height = oldimage.Height; command.Flags = RasterSizeFlags.Resample; command.Run(newimage); //This changes the entire image and all pages. There is no need to pageinate. // Save the image back to disk codecs.Save(newimage, destFileName, RasterImageFormat.Tif, oldimage.BitsPerPixel); // Clean Up newimage.Dispose(); oldimage.Dispose(); codecs.Dispose(); }
public static void ExportPdfImage(string filename) { var outputFile = Path.Combine(Leadtools.Demo.Support.Path.GetOutputPath(), Path.GetFileNameWithoutExtension(filename) + "_Image.pdf"); // Create instance of RasterCodecs object to load and save the file // https://www.leadtools.com/help/leadtools/v19/dh/co/leadtools.codecs~leadtools.codecs.rastercodecs.html using (var codecs = new RasterCodecs()) { // We want to load all the pages of the file codecs.Options.Load.AllPages = true; // Load the image // https://www.leadtools.com/help/leadtools/v19/dh/l/leadtools~leadtools.rasterimage.html using (var image = codecs.Load(filename)) { if (image.BitsPerPixel != 1) { // Use the AutoBinarize Command to convert the image to 1bpp (black and white) // https://www.leadtools.com/help/leadtools/v19/dh/po/leadtools.imageprocessing.core~leadtools.imageprocessing.core.autobinarizecommand.html new AutoBinarizeCommand().Run(image); } // Save the image out as a 1BPP CCITT Group 4 compressed PDF // https://www.leadtools.com/help/leadtools/v19/dh/co/leadtools.codecs~leadtools.codecs.rastercodecs~save.html codecs.Save(image, outputFile, RasterImageFormat.RasPdfG4, 1); } } }
public byte[] PublishToBytes() { RasterCodecs codec = tifEditor.Codecs; RasterImage image = tifEditor.Viewer.Image; using (new CursorBlock(Cursors.WaitCursor)) { using (var stream = new MemoryStream()) { int totalPages = tifEditor.Viewer.Image.PageCount; AnnAutomation annAutomation = tifEditor.AnnAutomation; for (int i = 1; i <= totalPages; ++i) { tifEditor.SetPageNumber(i); tifEditor.Viewer.Refresh(); annAutomation.Realize(); } codec.Save(image, stream, RasterImageFormat.TifxFaxG4, 0, 1, totalPages, 1, CodecsSavePageMode.Overwrite); // do I need this? // annAutomation.Container.Objects.Clear(); return(stream.GetBuffer()); } } }
public void ConvertTifToPdf(string SourceFileName, string DestFileName) { RasterCodecs CodecsCommand = new RasterCodecs(); RasterImage LeadImage = null; try { UnlockLeadToolsPDFSupport(); //RasterCodecs.CodecsPath = codecsPath; //CodecsCommand.Options.Pdf.InitialPath = pdfInitialPath; CodecsCommand.Options.Pdf.Save.UseImageResolution = true; CodecsCommand.Options.Tiff.Load.IgnoreViewPerspective = true; LeadImage = CodecsCommand.Load(SourceFileName); //LeadImage.ChangeCompression((LeadImage.IsSuperCompressed == true) ? RasterCompression.None : RasterCompression.Super); if (String.IsNullOrEmpty(DestFileName)) { DestFileName = System.IO.Path.Combine(System.IO.Path.GetTempPath().ToString(), Guid.NewGuid().ToString() + ".PDF"); } CodecsCommand.Save(LeadImage, DestFileName, Leadtools.RasterImageFormat.RasPdf, 1, 1, LeadImage.PageCount, 1, Leadtools.Codecs.CodecsSavePageMode.Overwrite); } finally { if (LeadImage != null) { LeadImage.Dispose(); } if (CodecsCommand != null) { CodecsCommand.Dispose(); } } }
public async void AddProfileImage(ContactModel contactItem, RasterImage image, Stream imageStream) { string imageFileName = Path.GetFileNameWithoutExtension(contactItem.Picture).Replace("image_", ""); string filePath = Path.Combine(HomePage.PROFILE_PICS_DIR, $"profile_{imageFileName}.jpeg"); if (imageStream != null) { await DependencyService.Get <IPictureSaver>().SaveImage(imageStream, filePath, PictureSaveResolution.Low, false); } else if (image != null) { LeadSize size = ImageSizeHelper.GetImageSize(image.Width, image.Height, PictureSaveResolution.Low); ResizeInterpolateCommand resizeInterpolateCommand = new ResizeInterpolateCommand(size.Width, size.Height, ResizeInterpolateCommandType.Resample); resizeInterpolateCommand.Run(image); using (var codecs = new RasterCodecs()) { codecs.Save(image, filePath, RasterImageFormat.Jpeg, 0); } } contactItem.ProfileImage = filePath; Device.BeginInvokeOnMainThread(() => profileImageView.Source = filePath); HomePage.Instance.SaveContactList(); }
/// <param name="yfile">源图像</param> /// <param name="mfile">新图像</param> /// <param name="p1">页码1</param> /// <param name="p2">页码2</param> /// <param name="fileformat">图像格式</param> public static bool _SplitImg(string yfile, string mfile, int p1, int p2, string fileformat) { try { RasterImageFormat format = new RasterImageFormat(); if (fileformat.IndexOf("jpg") >= 0) { format = RasterImageFormat.Jpeg; } else if (fileformat.IndexOf("pdf") >= 0) { format = RasterImageFormat.RasPdfJpeg; } else if (fileformat.IndexOf("tif") >= 0) { format = RasterImageFormat.TifJpeg; } RasterImage _imagepx; RasterCodecs _Codef = new RasterCodecs(); for (int i = p1; i <= p2; i++) { _imagepx = _Codef.Load(yfile, 0, CodecsLoadByteOrder.BgrOrGrayOrRomm, i, i); int bit = _imagepx.BitsPerPixel; if (bit != 1) { if (bit != 8) { // _Codef.Options.Jpeg.Save.QualityFactor = 80; _Codef.Save(_imagepx, mfile, format, bit, 1, 1, i, CodecsSavePageMode.Append); } else { // _Codef.Options.Jpeg.Save.QualityFactor = Factor; _Codef.Save(_imagepx, mfile, format, 8, 1, 1, i, CodecsSavePageMode.Append); } } else { _Codef.Save(_imagepx, mfile, format, 1, 1, 1, -1, CodecsSavePageMode.Append); } } _Codef.Dispose(); return(true); } catch { return(false); } }
static void Main(string[] args) { String fileToConvert = @"FILE PATH HERE"; RasterSupport.SetLicense(@"C:\LEADTOOLS 20\Common\License\LEADTOOLS.LIC", System.IO.File.ReadAllText(@"C:\LEADTOOLS 20\Common\License\LEADTOOLS.LIC.KEY")); using (RasterCodecs codecs = new RasterCodecs()) { using (IOcrEngine ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD, false)) { ocrEngine.Startup(null, null, null, @"C:\LEADTOOLS 20\Bin\Common\OcrLEADRuntime"); using (IOcrPage ocrPage = ocrEngine.CreatePage(ocrEngine.RasterCodecsInstance.Load(fileToConvert, 1), OcrImageSharingMode.AutoDispose)) { ocrPage.AutoZone(null); ocrPage.Recognize(null); string recognizedCharacters = ocrPage.GetText(-1); BarcodeEngine engine = new BarcodeEngine(); int resolution = 300; using (RasterImage image = RasterImage.Create((int)(8.5 * resolution), (int)(11.0 * resolution), 1, resolution, RasterColor.FromKnownColor(RasterKnownColor.White))) { BarcodeWriter writer = engine.Writer; QRBarcodeData data = BarcodeData.CreateDefaultBarcodeData(BarcodeSymbology.QR) as QRBarcodeData; data.Bounds = new LeadRect(0, 0, image.ImageWidth, image.ImageHeight); QRBarcodeWriteOptions writeOptions = writer.GetDefaultOptions(data.Symbology) as QRBarcodeWriteOptions; writeOptions.XModule = 30; writeOptions.HorizontalAlignment = BarcodeAlignment.Near; writeOptions.VerticalAlignment = BarcodeAlignment.Near; data.Value = recognizedCharacters; writer.CalculateBarcodeDataBounds(new LeadRect(0, 0, image.ImageWidth, image.ImageHeight), image.XResolution, image.YResolution, data, writeOptions); Console.WriteLine("{0} by {1} pixels", data.Bounds.Width, data.Bounds.Height); writer.WriteBarcode(image, data, writeOptions); CropCommand cmd = new CropCommand(new LeadRect(0, 0, data.Bounds.Width, data.Bounds.Height)); cmd.Run(image); codecs.Save(image, "QR.tif", RasterImageFormat.CcittGroup4, 1); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { var process = new Process(); process.StartInfo = new ProcessStartInfo("QR.tif") { UseShellExecute = true }; process.Start(); } Console.WriteLine(); } } } } }
public static MemoryStream ToStream(this RasterImage image, RasterImageFormat format, int compression) { MemoryStream fileStream = new MemoryStream(); _Codecs.Options.Jpeg.Save.QualityFactor = compression; _Codecs.Save(image, fileStream, format, 0); return(fileStream); }
private void UploadDownload() { try { // Set the credentials if (_serverProperties.UseCredentials) { _rasterCodecs.UriOperationCredentials = new NetworkCredential(_serverProperties.UserName, _serverProperties.Password, _serverProperties.Domain); } else { _rasterCodecs.UriOperationCredentials = CredentialCache.DefaultCredentials; } // Set the proxy if (_serverProperties.UseProxy) { _rasterCodecs.UriOperationProxy = new WebProxy(_serverProperties.Host, _serverProperties.Port); } else { _rasterCodecs.UriOperationProxy = null; } // Create the URL for the image string url = _serverProperties.Url; if (!url.EndsWith("/")) { url += "/"; } // Use the SharePoint Lists web service url += "Shared Documents/" + _imageFileName; Uri uri = new Uri(url); _imageServerName = uri.ToString(); // Upload or download this image if (_isDownloading) { _rasterImage = _rasterCodecs.Load(uri); } else { _rasterCodecs.Save(_rasterImage, uri, _rasterImage.OriginalFormat, 0); } CloseMe(true, null); } catch (Exception ex) { CloseMe(false, ex); } }
private static void ConvertPdfToTif(string fileName) { Func <int, string> getSaveFileName = pg => Path.GetDirectoryName(fileName) + Path.DirectorySeparatorChar + Path.GetFileNameWithoutExtension(fileName) + "_pg" + pg.ToString() + ".tif"; try { using (var codecs = new RasterCodecs()) { var info = codecs.GetInformation(fileName, true); for (var pageNumber = 1; pageNumber <= info.TotalPages; pageNumber++) { // Make sure the resulting img has the original resolution var pdfInfo = codecs.GetRasterPdfInfo(fileName, pageNumber); codecs.Options.RasterizeDocument.Load.XResolution = pdfInfo.XResolution; codecs.Options.RasterizeDocument.Load.YResolution = pdfInfo.YResolution; // Save the file using a format appropriate for the bits per pixel var bpp = pdfInfo.BitsPerPixel; var saveFormat = RasterImageFormat.Tif; if (bpp == 1) { saveFormat = RasterImageFormat.CcittGroup4; } else if (bpp > 1 && bpp < 9) { saveFormat = RasterImageFormat.TifLzw; } else if (bpp == 24) { saveFormat = RasterImageFormat.TifJpeg; } using (var page = codecs.Load(fileName, pageNumber)) codecs.Save(page, getSaveFileName(pageNumber), saveFormat, 0); } } Console.WriteLine("Done"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); } finally { Console.ReadLine(); } }
private void _miFileSaveCurrentAsAbc_Click(object sender, System.EventArgs e) { SaveFileDialog saveDlg = new SaveFileDialog(); saveDlg.FileName = _fileName.Remove(_fileName.Length - 4, 4); saveDlg.OverwritePrompt = true; string formatString = _quality; formatString = (formatString.Trim()).Substring(1, formatString.Length - 3); saveDlg.FileName += "_Abc_" + formatString + ".abc"; saveDlg.Title = "Save As ABC (LEAD ABC Format)"; saveDlg.Filter = "LEAD ABC Format (*.abc)|*.abc"; try { if (saveDlg.ShowDialog() == DialogResult.OK) { ViewerForm activeViewer = ActiveViewerForm; _codecs.Save(activeViewer.Image, saveDlg.FileName, RasterImageFormat.Abc, 1); } } catch (Exception ex) { Messager.ShowFileSaveError(this, saveDlg.FileName, ex); } }
private void SaveToFile(string fileName) { RasterCodecs codec = new RasterCodecs(); if (File.Exists(fileName)) { File.Delete(fileName); } for (int i = 0; i < destImageList.Items.Count; ++i) { codec.Save(destImageList.Items[i].Image, fileName, RasterImageFormat.Tif, 0, i + 1, i + 1, i + 1, CodecsSavePageMode.Append); } }
public void ResizeTiffImage(string SourceFileName, string DestFileName, bool convertToGrayScale, float percentOfOriginal) { using (RasterCodecs codecs = new RasterCodecs()) { // Load the source image using (RasterImage srcImage = codecs.Load(SourceFileName)) { //int destWidth = Convert.ToInt32((srcImage.Width)*percentOfOriginal); //int destHeight = Convert.ToInt32((srcImage.Height)*percentOfOriginal); int destWidth = Convert.ToInt32((srcImage.Width) * 0.5); int destHeight = Convert.ToInt32((srcImage.Height) * 0.5); RasterImage image = null; // Create the destination image //RasterImage destImage = new RasterImage( // RasterMemoryFlags.Conventional, // destWidth, // destHeight, // srcImage.BitsPerPixel, // srcImage.Order, // srcImage.ViewPerspective, // srcImage.GetPalette(), // IntPtr.Zero, // 0); if (image == null) { //Resize(destWidth, destHeight, srcImage); image = srcImage; } else { //Resize(destWidth, destHeight, srcImage); image.AddPage(srcImage); srcImage.Dispose(); } var bitsPerPixel = 24; if (convertToGrayScale) { bitsPerPixel = 12; } //Save the destination image codecs.Save(image, DestFileName, RasterImageFormat.Tif, bitsPerPixel); } } }
public void CompressImage(string SourceFileName, string DestFileName) { RasterCodecs codecs = new RasterCodecs(); RasterImage sourceImage = codecs.Load(SourceFileName); RasterImage destinationImage = new RasterImage( RasterMemoryFlags.Conventional, sourceImage.Width, sourceImage.Height, sourceImage.BitsPerPixel, sourceImage.Order, sourceImage.ViewPerspective, sourceImage.GetPalette(), IntPtr.Zero, 0); sourceImage.Access(); destinationImage.Access(); byte[] buffer = new byte[sourceImage.BytesPerLine]; for (int y = 0; y < sourceImage.Height; y++) { sourceImage.GetRow(y, buffer, 0, buffer.Length); destinationImage.SetRow(y, buffer, 0, buffer.Length); } destinationImage.Release(); sourceImage.Release(); // We do not need the source image anymore sourceImage.Dispose(); // save the destination image codecs.Save(destinationImage, DestFileName, RasterImageFormat.Tif, 24); // perform image processing on the image //FlipCommand flipCmd = new FlipCommand(); //flipCmd.Horizontal = false; //flipCmd.Run(destinationImage); //// save it //codecs.Save(destinationImage, destFileName2, RasterImageFormat.Bmp, 24); // Clean up destinationImage.Dispose(); codecs.Dispose(); codecs.Dispose(); }
public static void GrayscaleTransformerVersion11(string srcFileName, string DestFileName) { RasterCodecs codecs = new RasterCodecs(); UnlockLeadToolsDocumentSupport(); IRasterImage image = null; int pageCount = 0; image = codecs.Load(srcFileName); pageCount = image.PageCount; var bitsPerPixel = 12; codecs.Save(image, DestFileName, RasterImageFormat.Tif, bitsPerPixel, 1, pageCount, 1, CodecsSavePageMode.Append); image.Dispose(); }
public void SaveStreamToJpeg(Stream sourceImage, string imageName) { try { RasterCodecs.Startup(); rasterCodecs = new RasterCodecs(); img = rasterCodecs.Load(sourceImage); Leadtools.RasterImageFormat rif = Leadtools.RasterImageFormat.Jpeg; rasterCodecs.Save(img, imageName, rif, img.BitsPerPixel); } finally { img.Dispose(); RasterCodecs.Shutdown(); } }
/// <summary> /// Processes the request. /// </summary> /// <param name="Context">The context.</param> protected virtual void ProcessRequest(HttpListenerContext Context) { using (DicomDataSet ds = new DicomDataSet()) { try { string file = Context.Request.QueryString["file"]; RasterImage image = null; ds.Load(file, DicomDataSetLoadFlags.None); image = ds.GetImage(null, 0, 0, RasterByteOrder.Rgb | RasterByteOrder.Gray, DicomGetImageFlags.AutoApplyModalityLut | DicomGetImageFlags.AutoApplyVoiLut | DicomGetImageFlags.AllowRangeExpansion); if (image != null) { // // resize the image to smaller // MemoryStream stream = new MemoryStream(); SizeWithAspect(image); if (image.Signed || image.GrayscaleMode == RasterGrayscaleMode.OrderedInverse) { ConvertSignedToUnsignedCommand cmd = new ConvertSignedToUnsignedCommand(ConvertSignedToUnsignedCommandType.ShiftNegativeToZero); cmd.Run(image); } Monitor.Enter(this); try { _Codecs.Save(image, stream, RasterImageFormat.Jpeg, 8); Context.Response.ContentType = "image/jpeg"; Context.Response.ContentLength64 = stream.Length; Context.Response.OutputStream.Write(stream.ToArray(), 0, Convert.ToInt32(stream.Length)); Context.Response.OutputStream.Close(); } finally { Monitor.Exit(this); } } } catch { } } }
private static void ConvertDocumentToImage( string inputFile, string outputFile, RasterImageFormat outputFormat, int bitsPerPixel) { if (!File.Exists(inputFile)) { throw new ArgumentException($"{inputFile} not found.", nameof(inputFile)); } if (bitsPerPixel != 0 && bitsPerPixel != 1 && bitsPerPixel != 2 && bitsPerPixel != 4 && bitsPerPixel != 8 && bitsPerPixel != 16 && bitsPerPixel != 24 && bitsPerPixel != 32) { throw new ArgumentOutOfRangeException(nameof(bitsPerPixel), bitsPerPixel, $"Invalid {nameof(bitsPerPixel)} value"); } using (var codecs = new RasterCodecs()) { codecs.Options.RasterizeDocument.Load.XResolution = 300; codecs.Options.RasterizeDocument.Load.YResolution = 300; // indicates the start of a loop from the same source file codecs.StartOptimizedLoad(); var totalPages = codecs.GetTotalPages(inputFile); if (totalPages > 1 && !RasterCodecs.FormatSupportsMultipageSave(outputFormat)) { Console.WriteLine($"The {outputFormat} format does not support multiple pages.\n" + "The resulting file will only contain the only last page of the document."); } for (var pageNumber = 1; pageNumber <= totalPages; pageNumber++) { Console.WriteLine($"Loading and saving page {pageNumber}"); using (var rasterImage = codecs.Load(inputFile, bitsPerPixel, CodecsLoadByteOrder.Bgr, pageNumber, pageNumber)) codecs.Save(rasterImage, outputFile, outputFormat, bitsPerPixel, 1, -1, 1, CodecsSavePageMode.Append); } // indicates the end of the load for the source file codecs.StopOptimizedLoad(); } }
protected override void Run() { Progress(101, "Acquiring from scanner..."); RasterImage image = null;// = twainSession.AcquireToImage(TwainUserInterfaceFlags.Show | TwainUserInterfaceFlags.Modal); SetTransferMode(); twainSession.Acquire(TwainUserInterfaceFlags.Show | TwainUserInterfaceFlags.Modal); using (RasterCodecs codecs = MainForm.GetRasterCodecs()) { codecs.Save(image, saveLocation, format, 0); } image.Dispose(); base.Run(); }
private void ConvertFileFormat() { RasterCodecs codec = new RasterCodecs(); //codec.Options.s // CodecsLoadOptions options = new CodecsLoadOptions(); CodecsPdfLoadOptions options = codec.Options.Pdf.Load; //CodecsRtfLoadOptions options1 = codec.Options.Rtf.Load; //options1. RasterImage image = codec.Load(@"c:\leadtools\gas.pdf", 0, CodecsLoadByteOrder.RgbOrGray, 1, 1); codec.Save(image, @"c:\leadtools\gas.tif", RasterImageFormat.TifxFaxG4, 1, 1, image.PageCount, 1, CodecsSavePageMode.Overwrite); MessageBox.Show("Done"); }
public static Stream SaveImage(RasterImage image, RasterCodecs rasterCodecs, SaveImageFormat saveFormat, string mimeType, int bitsPerPixel, int qualityFactor) { // We need to find out the format, bits/pixel and quality factor // If the user gave as a format, use it if (saveFormat == null) { // If the user did not give us a format, use PNG saveFormat = new PngImageFormat(); mimeType = "image/png"; } saveFormat.PrepareToSave(rasterCodecs, image, bitsPerPixel, qualityFactor); // Save it to a memory stream var ms = new MemoryStream(); rasterCodecs.Save(image, ms, saveFormat.ImageFormat, saveFormat.BitsPerPixel); return(PrepareStream(ms, mimeType)); }
private void _mnuOverlaysSaveOverlay_Click(object sender, EventArgs e) { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "Windows Bitmap (*.bmp)|*.bmp"; dlg.FilterIndex = 0; if (dlg.ShowDialog() == DialogResult.OK) { int selected = _rasterImageList.Items.IndexOf(_rasterImageList.Items.GetSelected()[0]); RasterImage overlay = _rasterImageViewer.Image.GetOverlayImage(selected, RasterGetSetOverlayImageMode.Copy); RasterCodecs codecs = new RasterCodecs(); codecs.Save(overlay, dlg.FileName, RasterImageFormat.Bmp, overlay.BitsPerPixel); codecs.Dispose(); overlay.Dispose(); } }
public void ConvertToGrayScale(string SourceFileName, string DestFileName) { RasterImage image = null; RasterCodecs codecs = new RasterCodecs(); int pageCount = 0; image = codecs.Load(SourceFileName); pageCount = image.PageCount; //RasterImage resizedImage = ResizeImage(image, codecs); var bitsPerPixel = 12; //if (convertToGrayScale) // bitsPerPixel = 12; codecs.Save(image, DestFileName, RasterImageFormat.Tif, bitsPerPixel, 1, pageCount, 1, CodecsSavePageMode.Insert); image.Dispose(); codecs.Dispose(); }
public override byte[] GetImageData(AnnContainer container, LeadRectD bounds) { if (_image == null) { return(null); } using (var image = _image.Clone(bounds.ToLeadRect())) { using (var codecs = new RasterCodecs()) { using (var ms = new MemoryStream()) { codecs.Save(image, ms, RasterImageFormat.Png, Image.BitsPerPixel); return(ms.ToArray()); } } } }
public void ConvertPdfToTif(string SourceFileName, string DestFileName) { using (RasterCodecs codecs = new RasterCodecs()) { codecs.Options.Pdf.InitialPath = _pdfInitialPath;; PDFDocument document = new PDFDocument(SourceFileName); for (int pageNumber = 1; pageNumber <= document.Pages.Count; pageNumber++) { // Render the page into a raster image using (RasterImage image = document.GetPageImage(codecs, pageNumber)) { // Append to (or create if it does not exist) a TIFF file codecs.Save(image, DestFileName, RasterImageFormat.Tif, 24, 1, 1, -1, CodecsSavePageMode.Append); image.Dispose(); } } codecs.Dispose(); } }
private void SaveImage() { if (_imageViewer.Image != null) { try { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "PNG | *.png"; if (dlg.ShowDialog() == DialogResult.OK) { using (RasterCodecs codecs = new RasterCodecs()) { codecs.Save(_imageViewer.Image, dlg.FileName, RasterImageFormat.Png, 0); } } } catch (Exception ex) { Messager.ShowError(this, ex); } } }
public void ConvertDpi(string srcFileName, string destFileName) { RasterCodecs codecs = new RasterCodecs(); RasterImage image = codecs.Load(srcFileName); int newResolution = 300; //BR says all files need to be 300 DPI. This should probably be an enum. image.XResolution = newResolution; image.YResolution = newResolution; SizeCommand command = new SizeCommand(); command.Width = image.Width; command.Height = image.Height; command.Flags = RasterSizeFlags.Resample; command.Run(image); codecs.Save(image, destFileName, RasterImageFormat.Tif, image.BitsPerPixel); image.Dispose(); codecs.Dispose(); }
public static void FillSection_Png( object sender, Leadtools.Printer.EmfEventArgs e ) { ConsoleMethods.Info( "EMF Event: FillSection_Png" ); const string format = "png"; string path = Path.Combine( GetOutputRootPath(), format + @"\", GetRandomFileName( format ) ); Directory.CreateDirectory( Path.GetDirectoryName( path ) ); // Get the EMF in memory and save as PNG. Metafile metaFile = null; try { metaFile = new Metafile( e.Stream ); IntPtr hEmf = metaFile.GetHenhmetafile(); using ( RasterImage image = RasterImageConverter.FromEmf( hEmf, 0, 0, RasterColor.White ) ) { using ( RasterRegion region = new RasterRegion( new LeadRect( 20, 30, 100, 200 ) ) ) { image.SetRegion( null, region, RasterRegionCombineMode.Set ); new FillCommand( RasterColor.FromKnownColor( RasterKnownColor.Black ) ).Run( image ); } using ( RasterCodecs codecs = new RasterCodecs() ) { codecs.Options.Png.Save.QualityFactor = 9; codecs.Save( image, path, RasterImageFormat.Png, 32 ); } } ConsoleMethods.Success( "FillSection_Png: PNG saved. " ); ConsoleMethods.Verbose( path ); } catch ( Exception ex ) { ConsoleMethods.Error( ex.Message, 4000 ); } }
//fully qualified path & filename public LT11_DPI_Transformer(string srcFileName, string destFileName) { RasterCodecs codecs = new RasterCodecs(); //Read Original Values IRasterImage image = codecs.Load(srcFileName); //Change values and save a new file name int newResolution = 300; //BR says all files need to be 300 DPI. This should probably be an enum, db table or config file. // Load the source image from disk image.XResolution = newResolution; image.YResolution = newResolution; SizeCommand command = new SizeCommand(); command.Width = image.Width; command.Height = image.Height; command.Flags = RasterSizeFlags.Resample; command.Run(image); //This changes the entire image and all pages. There is no need to pageinate. codecs.Save(image, destFileName, RasterImageFormat.Tif, image.BitsPerPixel); image.Dispose(); }
void RealizeAnnotationV2() { try { // Create and set up the container AnnContainer container = new AnnContainer(); IntPtr hdc = RasterImagePainter.CreateLeadDC(_CurrCell.Image); container.Bounds = new AnnRectangle(0, 0, _CurrCell.Image.ImageWidth, _CurrCell.Image.ImageHeight); container.UnitConverter = new AnnUnitConverter(_CurrCell.Image.XResolution, _CurrCell.Image.YResolution); container.Draw(_CurrCell.Image); using (RasterCodecs _codecs = new RasterCodecs()) { _codecs.Save(_CurrCell.Image, _CurrCell.Image.Tags.ToString(), RasterImageFormat.DicomGray, _CurrCell.Image.BitsPerPixel); } } catch { } }
void SaveThumbnail(MedicalViewerCell _cell) { try { string _dcmFile = ""; if (_cell.Tag != null) _dcmFile = _cell.Tag.ToString(); int Detail_ID = _cell.TabIndex; if (_dcmFile.Trim() != "") { using (RasterCodecs _Codecs = new RasterCodecs()) { using (RasterImage _temp = _Codecs.Load(_dcmFile)) { _Codecs.Save(_temp.CreateThumbnail(83, 100, _temp.BitsPerPixel, _temp.ViewPerspective, RasterSizeFlags.Bicubic), thumbnailFileName, RasterImageFormat.Png, 8); UpdateThumbnailImgOnScheduled(thumbnailFileName,Detail_ID, 1); } } } } catch { } }
private static void DoExtraction(string srcFileName, string destFileName, int[] pageNumList, bool annotation) { RasterCodecs codec = new RasterCodecs(); RasterImage image = null; RasterTagMetadata[] tagsData = null; try { image = codec.Load(srcFileName); int pageCount = image.PageCount; if (annotation) { tagsData = new RasterTagMetadata[pageCount]; for (int i = 0; i < pageCount; ++i) { tagsData[i] = codec.ReadTag(srcFileName, i + 1, RasterTagMetadata.AnnotationTiff); } } int listCount = pageNumList.Length; if (File.Exists(destFileName)) { File.Delete(destFileName); } StatusForm statusForm = new StatusForm(); statusForm.LoadFormData(srcFileName, destFileName, listCount); statusForm.Show(); statusForm.Refresh(); for (int i = 0; i < listCount; ++i) { codec.Save(image, destFileName, RasterImageFormat.CcittGroup4, 1, pageNumList[i], pageNumList[i], i, CodecsSavePageMode.Append); if (annotation) { if ((tagsData != null) && (tagsData[pageNumList[i] - 1] != null)) { codec.WriteTag(destFileName, i + 1, tagsData[pageNumList[i]-1]); } } statusForm.ShowPageInfo(pageNumList[i]); } if (image.PageCount > listCount) { int deleteCount = 0; for (int i = 1; i <= pageCount; ++i) { if (PageNumberFound(i, pageNumList)) { image.RemovePageAt(i+deleteCount); deleteCount--; } } codec.Save(image, srcFileName, RasterImageFormat.CcittGroup4, 1, 1, image.PageCount, 1, CodecsSavePageMode.Overwrite); if (annotation) { int newPageIndex = 0; for (int i = 0; i < pageCount; ++i) { if (!PageNumberFound(i+1, pageNumList) && (tagsData != null) && (tagsData[i] != null)) { codec.WriteTag(srcFileName, ++newPageIndex, tagsData[i]); } } } } else { File.Delete(srcFileName); } statusForm.Close(); } finally { if (image != null) { image.Dispose(); } } }
private void SaveToFile(string fileName) { RasterCodecs codec = new RasterCodecs(); if (File.Exists(fileName)) { File.Delete(fileName); } for (int i=0;i<destImageList.Items.Count;++i){ codec.Save(destImageList.Items[i].Image, fileName, RasterImageFormat.Tif, 0, i + 1, i + 1, i + 1, CodecsSavePageMode.Append); } }