How to create black and white images in Magick.NET - c#

I would like create TIF, PNG, JPG and BMP like black and white images via
https://magick.codeplex.com.
What I found if I do like in my code I can generate only TIF black and why images but not images of other types.
Any clue how to fix it?
MagickReadSettings readSettings = new MagickReadSettings()
{
UseMonochrome = true
};
using (MagickImage image = new MagickImage(fileInfo.FullName, readSettings))
{
image.AddProfile(ColorProfile.SRGB);
if (Properties.Settings.Default.ImageFileExtentionToConvert.ToLower().Contains("tif"))
{
image.CompressionMethod = CompressionMethod.Group4;
image.ColorSpace = ColorSpace.Gray;
image.Format = MagickFormat.Tif;
}
else if (Properties.Settings.Default.ImageFileExtentionToConvert.ToLower().Contains("png"))
{
// image.ColorSpace = ColorSpace.Gray;
image.Settings.SetDefine(MagickFormat.Png, "compression-strategy", "0");
image.Settings.SetDefine(MagickFormat.Png, "compression-filter", "0");
image.Format = MagickFormat.Png;
}
else if (Properties.Settings.Default.ImageFileExtentionToConvert.ToLower().Contains("jpg"))
{
image.Settings.SetDefine(MagickFormat.Jpg, "compression-strategy", "0");
image.Settings.SetDefine(MagickFormat.Jpg, "compression-filter", "0");
image.Format = MagickFormat.Jpg;
}
else
{
image.CompressionMethod = CompressionMethod.NoCompression;
image.Format = MagickFormat.Bmp;
}
image.Write(newFileName);
}

I found the answer here https://magick.codeplex.com/discussions/637181
using (MagickImage image = new MagickImage(pathToTiffFile))
{
image.Threshold(60); // 60 is OK
image.Depth = 1;
image.Write(pathToOutputFile);
}

Related

Unable to capture screen of WkWebView in Xamarin IOS

I am trying to capture the screen in IOS, Other than WkWebview all other view component I am able to capture by below code.WkWebview is giving a blank page as captured data. If I am using UIWebview the same code working Is there anything specific to do to take screen shot WkWebView.
Code for screen capture.
public static UIImage SnapshotView(this UIView view)
{
UIGraphics.BeginImageContextWithOptions(view.Bounds.Size, false, UIScreen.MainScreen.Scale);
view.DrawViewHierarchy(view.Bounds, true);
var image = UIGraphics.GetImageFromCurrentImageContext();
UIGraphics.EndImageContext();
return image;
}
WkWebView Configuration:
WKWebView _wkWebView = new WKWebView(ReaderView.Frame, new WKWebViewConfiguration());
_wkWebView.LoadFileUrl(tempUrl, tempUrl);
_wkWebView.ContentMode = UIViewContentMode.ScaleToFill;
_wkWebView.BackgroundColor = UIColor.Clear;
_wkWebView.Opaque = false;
_wkWebView.ScrollView.BackgroundColor = UIColor.Clear;
//_wkWebView.DrawViewHierarchy(_wkWebView.Bounds, true);
ReaderView.AddSubview(_wkWebView);
var imag = _wkWebView.SnapshotView();
I fixed the issue by replacing the WKWebView with PdfView.I am using this view for loading PDFs.
The latest code is below
pdfView = new PdfView();
pdfView.TranslatesAutoresizingMaskIntoConstraints = false;
ReaderView.AddSubview(pdfView);
pdfView.LeadingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.LeadingAnchor).Active = true;
pdfView.TrailingAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TrailingAnchor).Active = true;
pdfView.TopAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.TopAnchor).Active = true;
pdfView.BottomAnchor.ConstraintEqualTo(View.SafeAreaLayoutGuide.BottomAnchor).Active = true;
// var path = Bundle.main.url(forResource: "test", withExtension: "pdf") else { return }
PdfDocument document;
// PdfDocument
using (urlString = new NSString(FilePath))
using (var tempUrl = NSUrl.CreateFileUrl(new string[] { urlString }))
document = new PdfDocument(tempUrl);
//if var document = PdfDocument(url: path) {
pdfView.Document = document;

How to make Generated gif in xamarin.ios slower?

I created a service used in my xamarin.forms project to generate a gif from four downloaded frame. The android side is working good, but I got a problem in iOs side, where gif is created but it's too fast, regardless of the set delay value. This is my class:
public class GifService : IGifService
{
public string CreateGif(string frame1Path, string frame2Path, string frame3Path, string frame4Path,string webId,string path="")
{
List<UIImage> listOfFrame = new List<UIImage>();
UIImage image1 = new UIImage(frame1Path);
listOfFrame.Add(image1);
UIImage image2 = new UIImage(frame2Path);
listOfFrame.Add(image2);
UIImage image3 = new UIImage(frame3Path);
listOfFrame.Add(image3);
UIImage image4 = new UIImage(frame4Path);
listOfFrame.Add(image4);
NSMutableDictionary fileProperties = new NSMutableDictionary();
fileProperties.Add(CGImageProperties.GIFLoopCount, new NSNumber(0));
NSMutableDictionary frameProperties = new NSMutableDictionary();
frameProperties.Add(CGImageProperties.GIFDelayTime, new NSNumber(5f));
NSUrl documentsDirectoryUrl = NSFileManager.DefaultManager.GetUrl(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User,null, true,out _);
NSUrl fileUrl = documentsDirectoryUrl.Append(webId + ".gif",false);
var destination = CGImageDestination.Create(fileUrl, MobileCoreServices.UTType.GIF, 4);
destination.SetProperties(fileProperties);
foreach(var frame in listOfFrame)
{
var cgImage = frame.CGImage;
if(cgImage!= null)
{
destination.AddImage(cgImage, frameProperties);
}
}
if (!destination.Close())
{
Console.WriteLine("Failed to finalize the image destination");
}
return fileUrl.Path;
}
}
I think that the problem is CGImageProperties.GIFDelayTime that is ignored, but i don't know why. How can I resolve this problem?
After some tries, I found finally a solution to generate a gif with a desired delay. I don't know why, but in the way i showed in my question, the options are ignored.
Here a working solution:
public class GifService : IGifService
{
public string CreateGif(string frame1Path, string frame2Path, string frame3Path, string frame4Path,string webId,string path="")
{
List<UIImage> listOfFrame = new List<UIImage>();
UIImage image1 = new UIImage(frame1Path);
listOfFrame.Add(image1);
UIImage image2 = new UIImage(frame2Path);
listOfFrame.Add(image2);
UIImage image3 = new UIImage(frame3Path);
listOfFrame.Add(image3);
UIImage image4 = new UIImage(frame4Path);
listOfFrame.Add(image4);
NSMutableDictionary fileProperties = new NSMutableDictionary
{
{ CGImageProperties.GIFLoopCount, new NSNumber(1) }
};
NSUrl documentsDirectoryUrl = NSFileManager.DefaultManager.GetUrl(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomain.User,null, true,out _);
NSUrl fileUrl = documentsDirectoryUrl.Append(webId + ".gif",false);
var destination = CGImageDestination.Create(fileUrl, MobileCoreServices.UTType.GIF, 4);
destination.SetProperties(fileProperties);
foreach (var frame in listOfFrame)
{
//difference is here, i create a var option and i set the
//GifDictionary
var options = new CGImageDestinationOptions();
options.GifDictionary = new NSMutableDictionary();
options.GifDictionary[CGImageProperties.GIFDelayTime] = new NSNumber(1f);
var cgImage = frame.CGImage;
if(cgImage!= null)
{
destination.AddImage(cgImage, options);
}
}
if (!destination.Close())
{
Console.WriteLine("Failed to finalize the image destination");
}
return fileUrl.Path;
}
}

Render a barcode in ASP.NET Web Form

i am trying to show the barcode in asp.net page. already download the zen barcode render with sample code. i tried the sample it is working fine with me. once i try in my code barcode label is showing empty. i checked with sample code and mine i did not find any difference , only data transfer is the different. this is what i tried.
<barcode:BarcodeLabel ID="BarcodeLabel1" runat="server" BarcodeEncoding="Code39NC" LabelVerticalAlign="Bottom" Text="12345"></barcode:BarcodeLabel>
if (!IsPostBack)
{
List<string> symbologyDataSource = new List<string>(
Enum.GetNames(typeof(BarcodeSymbology)));
symbologyDataSource.Remove("Unknown");
barcodeSymbology.DataSource = symbologyDataSource;
barcodeSymbology.DataBind();
}
this is the function
BarcodeSymbology symbology = BarcodeSymbology.Unknown;
if (barcodeSymbology.SelectedIndex != 0)
{
symbology = (BarcodeSymbology)1;
}
symbology = (BarcodeSymbology)1;
string text = hidID.Value.ToString();
string scaleText = "1";
int scale;
if (!int.TryParse(scaleText, out scale))
{
if (symbology == BarcodeSymbology.CodeQr)
{
scale = 3;
}
else
{
scale = 1;
}
}
else if (scale < 1)
{
scale = 1;
}
if (!string.IsNullOrEmpty(text) && symbology != BarcodeSymbology.Unknown)
{
barcodeRender.BarcodeEncoding = symbology;
barcodeRender.Scale = 1;
barcodeRender.Text = text;
}
symbology is set as Code39NC from the dropdown. scale is 1 and text is coming from other form the value is passing as well. still the bacodelable is showing only value not the barcode picture.
Here are two code samples using ZXing to create a (QR) barcode as both an image and as a base64 encoded string. Both of these options can be used with an <img /> tag to embed the barcode in the page.
This is not an ASP.NET control. It is a library that creates barcodes from text.
// First Text to QR Code as an image
public byte[] ToQRAsGif(string content)
{
var barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = this._h,
Width = this._w,
Margin = 2
}
};
using (var bitmap = barcodeWriter.Write(content))
using (var stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Gif);
stream.Position = 0;
return stream.GetBuffer();
}
}
// From Text to QR Code as base64 string
public string ToQRAsBase64String(string content)
{
var barcodeWriter = new BarcodeWriter
{
Format = BarcodeFormat.QR_CODE,
Options = new EncodingOptions
{
Height = _h,
Width = _w,
Margin = 2
}
};
using (var bitmap = barcodeWriter.Write(content))
using (var stream = new MemoryStream())
{
bitmap.Save(stream, ImageFormat.Gif);
return String.Format("data:image/gif;base64,{0}", Convert.ToBase64String(stream.ToArray()));
}
}
Hope this helps! Happy coding.
UPDATE: Here is the link to their product page on codeplex: https://zxingnet.codeplex.com/

Colour appears faded in corrected CMYK image

I am compressing a pdf containing a number of images. The below code I got while browsing for the PDF compression. It works fine for RBG format images but in case of CMYK format the images appears with inverted colours (as a negative). Somehow I was able to convert the inverted colours but the image colour got faded.
Please suggest how should I proceed. Thanks in advance.
{
PdfReader.unethicalreading = true;
string pdfFile = #"C:\TestPdf.pdf";
PdfReader reader = new PdfReader(pdfFile);
long quality = 50L;
int n = reader.XrefSize;
for (int i = 0; i < n; i++)
{
PdfObject obj = reader.GetPdfObject(i);
if (obj == null || !obj.IsStream()) { continue; }
PdfDictionary dict = (PdfDictionary)PdfReader.GetPdfObject(obj);
PdfObject pdfcolorspace = dict.Get(PdfName.COLORSPACE);
PdfName subType = (PdfName)PdfReader.GetPdfObject(dict.Get(PdfName.SUBTYPE));
if (!PdfName.IMAGE.Equals(subType)) { continue; }
PRStream stream = (PRStream)obj;
try
{
PdfImageObject image = new PdfImageObject(stream);
PdfName filter = (PdfName)image.Get(PdfName.FILTER);
if ( PdfName.JBIG2DECODE.Equals(filter) || PdfName.JPXDECODE.Equals(filter) || PdfName.CCITTFAXDECODE.Equals(filter) || PdfName.FLATEDECODE.Equals(filter))
continue;
System.Drawing.Image img = image.GetDrawingImage();
if (img == null) continue;
var ll = image.GetImageBytesType();
int width = img.Width;
int height = img.Height;
using (System.Drawing.Bitmap dotnetImg = new System.Drawing.Bitmap(img))
{
System.Drawing.Imaging.ImageCodecInfo codec = System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()[1];
System.Drawing.Imaging.EncoderParameters eParams = new System.Drawing.Imaging.EncoderParameters(1);
eParams.Param[0] = new System.Drawing.Imaging.EncoderParameter( System.Drawing.Imaging.Encoder.Quality, quality);
using (MemoryStream msImg = new MemoryStream())
{
dotnetImg.Save(msImg, codec, eParams);
msImg.Position = 0;
stream.Clear();
if (pdfcolorspace == PdfName.DEVICECMYK)
{
img.Save(msImg, ImageFormat.Jpeg);
stream.Put(PdfName.COLORSPACE, PdfName.DEVICECMYK);
}
else
{
stream.Put(PdfName.COLORSPACE, PdfName.DEVICERGB);
}
stream.SetData( msImg.ToArray(), true, PdfStream.BEST_COMPRESSION);
stream.Put(PdfName.TYPE, PdfName.XOBJECT);
stream.Put(PdfName.SUBTYPE, PdfName.IMAGE);
stream.Put(PdfName.FILTER, PdfName.DCTDECODE);
stream.Put(PdfName.WIDTH, new PdfNumber(width));
stream.Put(PdfName.HEIGHT, new PdfNumber(height));
stream.Put(PdfName.BITSPERCOMPONENT, new PdfNumber(8));
}
}
}
catch (Exception ex)
{
}
finally
{
reader.RemoveUnusedObjects();
}
}
PdfStamper stamper = new PdfStamper(reader, new FileStream(#"C:\Compress.pdf", FileMode.Create), PdfWriter.VERSION_1_5);
stamper.FormFlattening = false;
stamper.SetFullCompression();
stamper.Close();
reader.Close();
}

WatiN security exception solution?

I am using Watin to copy a image to the clipboard, I am getting this error when I do so,
is there a work around to this using AlertDialogHandler?
public System.Drawing.Image GetPicture(WatiN.Core.Image image, ref IE browser)
{
if (image == null || !image.Exists || string.IsNullOrEmpty(image.Src))
return null;
const string t_js =
#"var div = document.images[{0}];
div.contentEditable ='true';
var controlRange;
if(document.body.createControlRange)
{{
controlRange = document.body.createControlRange();
controlRange.addElement(div);
controlRange.execCommand('Copy');
}}
div.contentEditable = 'false';";
var cnt = -1;
foreach (var image1 in browser.Images)
{
cnt++;
if (image1 != null && image1.Exists && !string.IsNullOrEmpty(image1.Src) && image1.Src.ToLower() == image.Src.ToLower())
break;
}
var script = string.Format(t_js, cnt);
WatiN.Core.DialogHandlers.AlertDialogHandler alertDialogHandler = new WatiN.Core.DialogHandlers.AlertDialogHandler ();
using (new WatiN.Core.DialogHandlers.UseDialogOnce(browser.DialogWatcher, alertDialogHandler ))
{
browser.RunScript(script); // Exception comes here !!
alertDialogHandler.WaitUntilExists();
alertDialogHandler.OKButton.Click();
browser.WaitForComplete();
}
var data = Clipboard.GetDataObject();
if (data == null)
return null;
var q = data.GetFormats();
q.ToString();
var q2 = data.GetFormats(true);
q2.ToString();
if (data.GetDataPresent(DataFormats.Bitmap))
{
var img = data.GetData(DataFormats.Bitmap, true);
return img as System.Drawing.Image;
}
if (data.GetDataPresent(DataFormats.Dib))
{
var img = data.GetData(DataFormats.Dib, true);
return img as System.Drawing.Image;
}
if (data.GetDataPresent(DataFormats.EnhancedMetafile))
{
var img = data.GetData(DataFormats.EnhancedMetafile, true);
return img as System.Drawing.Image;
}
if (data.GetDataPresent(DataFormats.MetafilePict))
{
var img = data.GetData(DataFormats.MetafilePict, true);
return img as System.Drawing.Image;
}
if (data.GetDataPresent(DataFormats.Tiff))
{
var img = data.GetData(DataFormats.Tiff, true);
return img as System.Drawing.Image;
}
if (data.GetDataPresent(DataFormats.Serializable))
{
var img = data.GetData(DataFormats.Serializable, true);
return img as System.Drawing.Image;
}
return null;
}
Thanks!
image of the security exception:
I believe it has to do something with IE Security settings
Goto
Security Tab -> Select proper zone (Internet/Local/etc) -> Click on Custome Level button -> Enable (Scripting - > Allow programmatic clipboard access)

Categories

Resources