I have been working on a small application to get fingerprints after 3 scanned. I used the ZKFingerSDK and when trying to get the register finger prints it brings the image back as black. I am using the ZK9500 device
if (RegisterCount >= REGISTER_FINGER_COUNT && !bIdentify)
{
RegisterCount = 0;
ret = GenerateRegisteredFingerPrint(); // <--- GENERATE FINGERPRINT TEMPLATE
if (zkfp.ZKFP_ERR_OK == ret)
{
ret = AddTemplateToMemory(); // <--- LOAD TEMPLATE TO MEMORY
if (zkfp.ZKFP_ERR_OK == ret) // <--- ENROLL SUCCESSFULL
{
string fingerPrintTemplate = string.Empty;
zkfp.Blob2Base64String(newRegTmp, cbCapTmp, ref fingerPrintTemplate);
newRegTmp = zkfp.Base64String2Blob(fingerPrintTemplate);
Bitmap bmp2;
MemoryStream ms2 = new MemoryStream();
BitmapFormat.GetBitmap(newRegTmp, mfpWidth, mfpHeight, ref ms2);
bmp2 = new Bitmap(ms2);
this.pictureBox1.Image = bmp2;
Console.WriteLine("finger print" + fingerPrintTemplate);
textRes.AppendText("merged " + fingerPrintTemplate + "\n");
}
}
}
I assume ret = AddTemplateToMemory(); loads the template into newRegTmp.
zkfp.Blob2Base64String(newRegTmp, cbCapTmp, ref fingerPrintTemplate); from this line i understand that you have the rawdata of the fingerprint at newRegTmp and you are extracting the size of cbCapTmp into fingerPrintTemplate.
In that case, you should not use newRegTmp in next line newRegTmp =zkfp.Base64String2Blob(fingerPrintTemplate); , which overwrites the actual data with the Base64 string. You can use Base64 string for displaying image on the web page with img tag. But to convert the raw data into image, you need to pass the actual data to GetBitMap.
If the above suggestion doesnt work, please share the implementation of AddTemplateToMemory.
Related
I was having trouble editing or removing keywords from a photograph. The following works to replace the keywords successfully:
...
string s_keywords = "tag1;tag2;tag3";
PropertyItem item_keyword = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));
item_keyword.Id = 0x9c9e; // XPKeywords
item_keyword.Type = 1;
item_keyword.Value = System.Text.Encoding.Unicode.GetBytes(s_keywords + "\0");
item_keyword.Len = item_keyword.Value.Length;
image.SetPropertyItem(item_keyword);
...
Note that my experiments show that image.RemovePropertyItem(0x9c9e); seems to have no effect on the saved image. Instead use the above code with s_keywords = "";
Don't do it this way: The following code works to remove the keywords, but results in the jpeg being re-encoded and loosing some quality (the image file goes from about 4MB to < 2MB and I can see some slight visual differences):
...
Image image_copy = new Bitmap(image);
foreach (var pi in image.PropertyItems)
{
if (pi.Id != 0x9c9e) image_copy.SetPropertyItem(pi);
}
image.Dispose();
image = (Image)image_copy.Clone();
...
I'm was having similar issues with setting the XPTitle - setting the propertyItem 0x9c9b seemed to have no effect in the saved image, instead I had to open the file as a BitmapFrame, extract the BitmapMetadata and use the Title property, then build a new jpeg using JpegBitmapEncoder - thus re-encoding and loosing image quality.
...
BitmapFrame bf_title = BitmapFrame.Create(new Uri(tmp_file, UriKind.Relative));
BitmapMetadata bmd_title = (BitmapMetadata)bf_title.Metadata.Clone();
bmd_title.Title = new_title;
BitmapFrame bf_new = BitmapFrame.Create(bf_title, bf_title.Thumbnail, bmd_title, bf_title.ColorContexts);
JpegBitmapEncoder je = new JpegBitmapEncoder();
je.Frames.Add(bf_new);
FileStream fs = new FileStream(tmp_file, FileMode.Create);
je.Save(fs);
fs.Close();
...
See my answer below for the correct way to change the title.
This was driving me crazy, I hope this can help someone else...
Note that the above keywords code now works perfectly.
I'm answering this because I could not find sample code to do this when I searched - so hopefully someone else will find this useful.
To change the title use the following code. The problem was that there are two tags that affect how windows shows the title - one of which (0x010e) takes priority over the XPTitle (0xc9b) tag...
...
string new_value = "New title for the image";
PropertyItem item_title = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));
item_title.Id = 0x9c9b; // XPTitle 0x9c9b
item_title.Type = 1;
item_title.Value = System.Text.Encoding.Unicode.GetBytes(new_value + "\0");
item_title.Len = item_title.Value.Length;
image.SetPropertyItem(item_title);
PropertyItem item_title2 = (PropertyItem)FormatterServices.GetUninitializedObject(typeof(PropertyItem));
item_title2.Id = 0x010e; // ImageDescription 0x010e
item_title2.Type = 2;
item_title2.Value = System.Text.Encoding.UTF8.GetBytes(new_value + "\0");
item_title2.Len = item_title2.Value.Length;
image.SetPropertyItem(item_title2);
image.Save("new_filename.jpg", ImageFormat.Jpeg)
image.Dispose();
...
Note - Another potential issue, you need to save the image to a new location. You can then dispose of the image and copy it into the original location if desired.
I've implemented a class that reads 24 bit-per-pixel TIFF generated by Microsoft.Reporting.WinForms.ReportViewer, converts it to a 1 bit-per-pixel TIFF and stores the result into a file.
This part is working just fine - I'm able to open the resulting TIFF in a TIFF viewer and view the contents.
For compression I'm using the following codec:
outImage.SetField(TiffTag.COMPRESSION, Compression.CCITT_T6);
Now I'm trying to read the same 1 bit-per-pixel TIFF and decompress it. I wrote the following methods:
public static void DecompressTiff(byte[] inputTiffBytes)
{
using (var tiffStream = new MemoryStream(inputTiffBytes))
using (var inImage = Tiff.ClientOpen("in-memory", "r", tiffStream, new TiffStream()))
{
if (inImage == null)
return null;
int totalPages = inImage.NumberOfDirectories();
for (var i = 0; i < totalPages; )
{
if (!inImage.SetDirectory((short) i))
return null;
var decompressedTiff = DecompressTiff(inImage);
...
}
private static byte[] DecompressTiff(Tiff image)
{
// Read in the possibly multiple strips
var stripSize = image.StripSize();
var stripMax = image.NumberOfStrips();
var imageOffset = 0;
int row = 0;
var bufferSize = image.NumberOfStrips() * stripSize;
var buffer = new byte[bufferSize];
int height = 0;
var result = image.GetField(TiffTag.IMAGELENGTH);
if (result != null)
height = result[0].ToInt();
int rowsperstrip = 0;
result = image.GetField(TiffTag.ROWSPERSTRIP);
if (result != null)
rowsperstrip = result[0].ToInt();
if (rowsperstrip > height && rowsperstrip != -1)
rowsperstrip = height;
for (var stripCount = 0; stripCount < stripMax; stripCount++)
{
int countToRead = (row + rowsperstrip > height) ? image.VStripSize(height - row) : stripSize;
var readBytesCount = image.ReadEncodedStrip(stripCount, buffer, imageOffset, countToRead); // Returns -1 for the last strip of the very first page
if (readBytesCount == -1)
return null;
imageOffset += readBytesCount;
row += rowsperstrip;
}
return buffer;
}
The problem is that when ReadEncodedStrip() is called for the last strip of the very first page - it returns -1, indicating that there is an error. And I can't figure out what's wrong even after debugging LibTIFF.NET decoder code. It's something with EOL TIFF marker discovered where it's not expected.
By some reason, LibTIFF.NET can't read a TIFF produced by itself or most likely I'm missing something. Here is the problem TIFF.
Could anyone please help to find the root cause?
After a more than a half day investigation, I've finally managed to detect the cause of this strange issue.
To convert from 24 bit-per-pixel TIFF to 1 bit-per-pixel, I ported algorithms from C to C# of the the 2 tools shipping with original libtiff: tiff2bw and tiffdither.
tiffdither has the bug that it doesn't include last image row in the output image, i.e. if you feed to it an image with 2200 rows height, you get the image with 2199 rows height as output.
I've noticed this bug in the very beginning of the porting and tried to fix, but, as it turned out eventually, not completely and the ported algorithm actually didn't write the last row via WriteScanline() method to the output TIFF. So this was the reason why LibTIFF.NET wasn't able to read last strip\row of the image depending on what reading method I used.
What was surprising to me is that LibTIFF.NET allows to write such actually corrupted TIFF without any error during writing. For example WriteDirectory() method returns true in this situation when image height set via TiffTag.IMAGELENGTH differs from the actual coount of rows written to it. However, later it can't read such the image and the error is thrown while reading.
Maybe this behavior inherited from the original libtiff, though.
I have a Word document (referred to as "doc" in the code below) with a bunch of .jpg images. Some of them have text wrapped around them (= Shapes), some of them don't (= InlineShapes). I am able to save the InlineShapes like so:
InlineShape ils = doc.InlineShapes[1];
ils.Select();
application.Selection.Copy();
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Bitmap)) {
Image image = (Image)data.GetData(DataFormats.Bitmap, true);
image.Save("c:\\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
But if I try to get the other ones by replacing the first two lines with these –
Shape s = doc.Shapes[1];
s.Select();
– it won't work. And if I check the formats with "data.GetFormats()" I notice that Bitmap isn't listed, which explains why it doesn't work. Instead it lists the "Office Drawing Shape Format". I suppose that I should try to convert the Shape to a InlineShape somehow, but I haven't been able to make it work. When I try to do it like this –
s.ConvertToInlineShape();
– I get an "invalid parameter" exception.
OK, the problem seems to have been that I tried to convert it at the wrong time. If I loop through all Shapes and convert them before trying to do anything else it works fine.
int number = doc.InlineShapes.Count;
MessageBox.Show(number.ToString()); // 0 to begin with
foreach (Microsoft.Office.Interop.Word.Shape s in doc.Shapes) {
MessageBox.Show(s.Type.ToString());
if (s.Type.ToString() == "msoTextBox") {
MessageBox.Show(s.TextFrame.TextRange.Text);
} else if (s.Type.ToString() == "msoPicture") {
s.ConvertToInlineShape();
}
}
number = doc.InlineShapes.Count;
MessageBox.Show(number.ToString()); // Now it's 1 as it should be
InlineShape ils = doc.InlineShapes[1];
ils.Select();
application.Selection.Copy();
IDataObject data = Clipboard.GetDataObject();
if (data.GetDataPresent(DataFormats.Bitmap)) {
Image image = (Image)data.GetData(DataFormats.Bitmap, true);
image.Save("c:\\image.jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
}
My current code writes a qr code but it over writes my file with just the qr code. I am not sure how to adjust the size of the qr code to be placed in one corner of the document rather than taking up the whole page. Also not sure if the RasterImage.Create means that it creates a new file with just the qr and discard my original file?
Code: - Convert PDF to Bmp to add QR then saving back to PDF
public void PDFFileExample()
{
RasterCodecs codecs1 = new RasterCodecs();
codecs1.Options.Pdf.InitialPath = #"C:\LEADTOOLS 18\Bin\Dotnet4\Win32";
codecs1.Dispose();
RasterCodecs codecs2 = new RasterCodecs();
codecs2.ThrowExceptionsOnInvalidImages = true;
System.Diagnostics.Debug.Assert(codecs2.Options.Pdf.InitialPath == #"C:\LEADTOOLS 18\Bin\Dotnet4\Win32");
string pdfFile = #"C:\QRCodeTesting\bottomRight.pdf";
string destFileName1 = #"C:\QRCodeTesting\bottomRightOutputTemp.pdf";
string destFileName2 = #"C:\QRCodeTesting\bottomRightOutput.bmp";
RasterCodecs codecs = new RasterCodecs();
if (codecs.Options.Pdf.IsEngineInstalled)
{
// Resulting image pixel depth.
codecs.Options.Pdf.Load.DisplayDepth = 24;
codecs.Options.Pdf.Load.GraphicsAlpha = 4;
codecs.Options.Pdf.Load.Password = "";
// Type of font anti-aliasing to use.
codecs.Options.Pdf.Load.TextAlpha = 1;
codecs.Options.Pdf.Load.UseLibFonts = true;
// Horizontal,vertical display resolution in dots per inch.
codecs.Options.RasterizeDocument.Load.XResolution = 150;
codecs.Options.RasterizeDocument.Load.YResolution = 150;
using (RasterImage image = codecs.Load(pdfFile, 0, CodecsLoadByteOrder.BgrOrGray, 1, 1))
{
// Set the PDF version to be v1.4
codecs.Options.Pdf.Save.Version = CodecsRasterPdfVersion.V14;
try
{
// Save the image back as PDF
codecs.Save(image, destFileName1, RasterImageFormat.RasPdf, 24);
}
catch (RasterException ex)
{
if (ex.Code == RasterExceptionCode.FileFormat)
MessageBox.Show(string.Format("Image in file {0} is loaded", destFileName1));
else
{
MessageBox.Show(string.Format("Could not load the file {0}.{1}{2}", destFileName1, Environment.NewLine, ex.Message));
}
}
}
// And load it back before saving it as BMP
using (RasterImage image = codecs.Load(destFileName1))
{
codecs.Save(image, destFileName2, RasterImageFormat.Bmp, image.BitsPerPixel);
writeQRTag(destFileName2);
}
}
else
{
MessageBox.Show("PDF Engine is not found!");
}
// Clean up
codecs.Dispose();
}
QRCode writing Method
private void writeQRTag(string imageFileName)
{
BarcodeEngine engine = new BarcodeEngine();
// Create the image to write the barcodes to
int resolution = 300;
using (RasterImage image = RasterImage.Create((int)(8.5 * resolution), (int)(11.0 * resolution), 1, resolution, RasterColor.FromKnownColor(RasterKnownColor.Red)))
{
// Write two QR barcodes
WriteQRCode(engine.Writer, image, QRBarcodeSymbolModel.Model1AutoSize, "QR Data 1", true);
// Save the image
using (RasterCodecs codecs = new RasterCodecs())
{
codecs.Save(image, imageFileName, RasterImageFormat.CcittGroup4, 1);
}
}
}
This is Maen from LEADTOOLS support.
I checked your code and noticed the following:
1) When you call RasterImage.Create() method, it will create a new RasterImage object that contains an empty red image, which you subsequently pass to the writeQRTag() function then save using the given file name.
When you save it, the red color is replaced by black because the file format you used only supports black and white. Since you're using a new image, the old image is lost (overwritten).
If you want to write the barcode on the image from the original file, you should NOT create a new image. Instead, you need to use the image you already loaded using codecs.Load() and write the barcode on it.
2) The code performs multiple load and save operations. Normally, you don't need to do that unless your application needs the different file formats (PDF, BMP and TIFF).
3) You create different instances of our RasterCodecs object but actually use only one of them. There's no need for 3 of the 4 RasterCodecs objects in the code.
If you still face problems with the code that uses our toolkit, you can send us the details in an email to support#leadtools.com and we will try to help you.
am trying to convert pdftoimage using the below link
http://threebit.net/mail-archive/itext-questions/msg00436.html
but i get this error how to get this code to work ?
"The type or namespace name 'PdfDecoder' could not be found"
am looking for open source .
this ghostscript dint work on server ,
http://www.codeproject.com/KB/webforms/aspnetpdfviewer.aspx
help me.
you Can try this.....
pdfDoc = (Acrobat.CAcroPDDoc)
Microsoft.VisualBasic.Interaction.CreateObject("Ac roExch.PDDoc", "");
int ret = pdfDoc.Open(inputFile);
if (ret == 0)
{
throw new FileNotFoundException();
}
// Get the number of pages (to be used later if you wanted to store that information)
int pageCount = pdfDoc.GetNumPages();
// Get the first page
pdfPage = (Acrobat.CAcroPDPage)pdfDoc.AcquirePage(0);
pdfPoint = (Acrobat.CAcroPoint)pdfPage.GetSize();
pdfRect = (Acrobat.CAcroRect)
Microsoft.VisualBasic.Interaction.CreateObject("Ac roExch.Rect", "");
pdfRect.Left = 0;
pdfRect.right = pdfPoint.x;
pdfRect.Top = 0;
pdfRect.bottom = pdfPoint.y;
// Render to clipboard, scaled by 100 percent (ie. original size)
// Even though we want a smaller image, better for us to scale in .NET
// than Acrobat as it would greek out small text
pdfPage.CopyToClipboard(pdfRect, 0, 0, 100);
IDataObject clipboardData = Clipboard.GetDataObject();
if (clipboardData.GetDataPresent(DataFormats.Bitmap))
{
Bitmap pdfBitmap =
(Bitmap)clipboardData.GetData(DataFormats.Bitmap);
}
pls take a look at this link For more info
you can try this one also
SautinSoft.PdfFocus f = new SautinSoft.PdfFocus();
f.ConvertPdfToImage(#"c:\sample.pdf", #"c:\pages\",
SautinSoft.PdfFocus.eImageFormat.Jpeg, 200);
pls go through this link for more info