ABCPDF 8 - How do I create a layered PDF - abcpdf

I need to use ABCPDF to create a layered PDF file. I've seen examples for watermarks but I need to have a PDF be the second layer. My code is below. When I run it, I only see one layer. What am I doing incorrectly?
Thank you.
WebSupergoo.ABCpdf8.Doc artworkDoc = new WebSupergoo.ABCpdf8.Doc();
artworkDoc.SetInfo(0, "License", _License);
WebSupergoo.ABCpdf8.Doc cutDoc = new WebSupergoo.ABCpdf8.Doc();
cutDoc.SetInfo(0, "License", _License);
// Attempt to read in Artwork File
try
{
artworkDoc.Read(ArtworkPath);
}
catch (Exception ex)
{
Exception noartwork = new Exception("Problem with Artwork File: " + ex.ToString());
throw noartwork;
}
// Attempt to read in cut File
try
{
cutDoc.Read(cutPath);
}
catch (Exception ex)
{
Exception nocut = new Exception("Problem with cut File: " + ex.ToString());
throw nocut;
}
WebSupergoo.ABCpdf8.Doc outputDoc = artworkDoc;
outputDoc.SetInfo(0, "License", _License);
// Attempt to merge artwork and cut files into output Document
try
{
outputDoc.PageNumber = 1;
outputDoc.Layer = outputDoc.LayerCount + 1;
outputDoc.AddImageDoc(cutDoc, 1, outputDoc.Rect);
}
catch (Exception ex)
{
Exception problem = new Exception("Problem appending cut and artwork files to output: " + ex.ToString());
throw problem;
}
// Attempt to save the output Document to the specified output path
try
{
outputDoc.Save(OutputPath);
artworkDoc.Clear();
cutDoc.Clear();
outputDoc.Clear();
}
catch (Exception ex)
{
Exception invalidOutput = new Exception("Unable to write output file: " + ex.ToString());
throw invalidOutput;
}
return true;
}

After resorting to using iTextSharp for some other PDF layer issues I had, I decided to explore how to use iTextSharp to create a new layered PDF file where the layers are pages from existing PDF files. The below code is what I came up with. The code presumes each of the source PDF files only has one page to add as a layer to the new PDF. It took me awhile to figure out so hopefully posting it here will help save others some time.
try
{
iTextSharp.text.pdf.PdfReader artwork = new iTextSharp.text.pdf.PdfReader(#”c:\artwork.pdf”);
iTextSharp.text.pdf.PdfReader cut = new iTextSharp.text.pdf.PdfReader(#”c:\cut.pdf”);
//get size of the cut PDF so the new layered PDF will be sized the same.
iTextSharp.text.Rectangle pageSize = new iTextSharp.text.Rectangle(cut.GetPageSize(1).Width, cut.GetPageSize(1).Height);
//the artwork PDF needs to be sized the same as the cut pdf
if (artwork.GetPageSize(1).Width != pageSize.Width || artwork.GetPageSize(1).Height != pageSize.Height)
{
string resizedFile = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(textBox1.Text),System.IO.Path.GetFileNameWithoutExtension(textBox1.Text) + "_resized.pdf");
iTextSharp.text.Document resizedArtwork = new iTextSharp.text.Document(pageSize);
iTextSharp.text.pdf.PdfWriter resizedWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(resizedArtwork, new System.IO.FileStream(resizedFile, System.IO.FileMode.Create));
iTextSharp.text.pdf.PdfImportedPage importedPage = resizedWriter.GetImportedPage(artwork, 1);
resizedArtwork.Open();
iTextSharp.text.pdf.PdfContentByte resizedContentByte = resizedWriter.DirectContent;
resizedContentByte.AddTemplate(importedPage, 0, 0);
resizedArtwork.Close();
//close reader associated with non-resized document
artwork.Close();
//set reader to resized document
artwork = new iTextSharp.text.pdf.PdfReader(resizedFile);
}
//create a new PDF
string outputFileName = #”c:\layered.pdf”;
iTextSharp.text.Document newPDF = new iTextSharp.text.Document(pageSize);
//create writer to output new PDF's contents to
iTextSharp.text.pdf.PdfWriter pdfWriter = iTextSharp.text.pdf.PdfWriter.GetInstance(newPDF, new System.IO.FileStream(outputFileName,System.IO.FileMode.Create));
//grab the first page from the artwork and cut PDF. These will become new layers in the new PDF
iTextSharp.text.pdf.PdfImportedPage artworkImportedPage = pdfWriter.GetImportedPage(artwork, 1);
iTextSharp.text.pdf.PdfImportedPage cutImportedPage = pdfWriter.GetImportedPage(cut, 1);
newPDF.Open();
iTextSharp.text.pdf.PdfContentByte pdfContentByte = pdfWriter.DirectContent;
pdfContentByte.BeginLayer(new iTextSharp.text.pdf.PdfLayer("artwork",pdfWriter));
pdfContentByte.AddTemplate(artworkImportedPage, 0, 0);
pdfContentByte.EndLayer();
pdfContentByte.BeginLayer(new iTextSharp.text.pdf.PdfLayer("cut", pdfWriter));
pdfContentByte.AddTemplate(cutImportedPage, 0, 0);
pdfContentByte.EndLayer();
newPDF.Close();
pdfWriter.Close();
artwork.Close();
cut.Close();
}
catch (Exception ex)
{
}

Related

Cognitive face detection is not working when I try to upload the image with a face mask

Any suggestions on how to get info of the image with a mask in cognitive face recognition?
When I upload image with headwear or eyeglasses then cognitive service returns the image information but when picking an image with mask, Cognitive service doesn't return any information. That means my implementation of cognitive service is not able to recognize the image with the mask. If anybody has faced this issue and resolved it please suggest me a solution.
public string subscriptionKey = "88c**************************f7";
public string uriBase = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect";
//Method to pick an image from the gallery
async void btnPick_Clicked(object sender, System.EventArgs e)
{
try
{
if (!CrossMedia.Current.IsPickPhotoSupported)
{
return;
}
var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium
});
if (file == null) return;
imgSelected.Source = ImageSource.FromStream(() => {
var stream = file.GetStream();
return stream;
});
MakeAnalysisRequest(file.Path);
}
catch (Exception ex)
{
string test = ex.Message;
}
}
> //convert Convert image to byte array
public byte[] GetImageAsByteArray(string imageFilePath)
{
using (FileStream fileStream =
new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
{
BinaryReader binaryReader = new BinaryReader(fileStream);
return binaryReader.ReadBytes((int)fileStream.Length);
}
}
> //Method to get image information from the detection Url
public async void MakeAnalysisRequest(string imageFilePath)
{
HttpClient client = new HttpClient();
client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
string requestParameters = "returnFaceId=true&returnFaceLandmarks=false" +
"&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses," +
"emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";
string uri = uriBase + "?" + requestParameters;
HttpResponseMessage response;
byte[] byteData = GetImageAsByteArray(imageFilePath);
using (ByteArrayContent content = new ByteArrayContent(byteData))
{
content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response = await client.PostAsync(uri, content);
string contentString = await response.Content.ReadAsStringAsync();
//***************************************************
//Here it return null in case of mask else its working fine
//***************************************************
List<ResponseModel> faceDetails = JsonConvert.DeserializeObject<List<ResponseModel>>(contentString);
if (faceDetails.Count != 0)
{
lblTotalFace.Text = "Total Faces : " + faceDetails.Count;
lblGender.Text = "Gender : " + faceDetails[0].faceAttributes.gender;
lblAge.Text = "Total Age : " + faceDetails[0].faceAttributes.age;
Console.WriteLine(faceDetails[0].faceAttributes.accessories.FirstOrDefault(x => x.type == "mask").confidence);
}
}
}
There a 2 different things that you must have in mind:
Some faces might not be seen by the services, see doc:
Some faces might not be detected because of technical challenges.
Extreme face angles (head pose) or face occlusion (objects such as
sunglasses or hands that block part of the face) can affect detection.
Frontal and near-frontal faces give the best results.
There are currently 2 detection models in Face API: "detection_01" and "detection_02". This latest model (existing since May 2019 if I remember well) has better performances (especially for rotated or partially hidden faces) but is not providing all the information in output that model 1 is giving.
Difference in detection models
I made a quick demo using a the "Cognitive Workbench" demo portal (available here) with the following image:
With detection_01: no face found
With detection_02: the face is found, as you can see in this capture:
But if you need to use specific attributes from the face, this might not solve your problem. See API documentation extract:

Xamarin.Forms Android save image to gallery

I have a stream which is the result of taking a photo. I want to save that photo to the users Gallery.
I have tried all manner of things but nothing takes... The class I am saving is a plain C# class - it does not inherit form any android types but that could be done if necessary (to fire an intent perhaps - though I tried this and it ended up another rabbit hole)
I have tried this:
try{
using (FileStream fs = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + _name, FileMode.OpenOrCreate))
{
fs.Write(bytes, 0, bytes.Length);
}
} catch (Exception ex) {
Console.WriteLine (ex.Message);
}
and also:
if (_filename.ToLower ().Contains (".jpg") || _filename.ToLower ().Contains (".png")) {
stream.Position = 0;
var bitmap = BitmapFactory.DecodeStream (stream);
var finalStream = new MemoryStream ();
bitmap.Compress (Bitmap.CompressFormat.Jpeg, 25, finalStream);
bitmap = null;
finalStream.Position = 0;
var path2 = Environment.GetFolderPath (Environment.SpecialFolder.MyPictures);
var filename2 = System.IO.Path.Combine (path2, _filename);
using (var fileStream = File.Create (filename2)) {
finalStream.Seek (0, SeekOrigin.Begin);
finalStream.CopyTo (fileStream);
fileStream.Close ();
finalStream.Dispose ();
stream.Dispose ();
fileStream.Dispose ();
GC.Collect ();
}
return;
}
I thought this would be an easy task! meh...
Any help?
Use the MediaStore ContentProvider. MediaStore.Images.Media has several Insert methods you can use to add content to the gallery.

"Parameter is not valid" error when extracting images using iTextSharp from a PDF containing JPXDecode filter

I am trying to extract images from a PDF using the following code. It works well for some filters like DCTDecode , but is not working for JPXDEcode ."Parameter not valid " error occurs at the point image.GetDrawingImage() is called.
using System.Drawing.Imaging;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
...
PdfReader pdf = new PdfReader(currfilename);
PdfReaderContentParser parser = new PdfReaderContentParser(pdf);
ImageRender listener = new ImageRender();
for (int i = 1; i <= pdf.NumberOfPages; i++)
{
try
{
parser.ProcessContent(i, listener);//calls RenderImage() at this point
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
public void RenderImage(ImageRenderInfo renderInfo)
{
PdfImageObject image = renderInfo.GetImage();
PdfName filter = image.Get(PdfName.FILTER) as PdfName;
if (renderInfo.GetRef() != null && image != null)
{
using (System.Drawing.Image dotnetImg = image.GetDrawingImage())//exception occurs at this point
{
if (dotnetImg != null)
{
ImageNames.Add(string.Format("{0}.tiff", renderInfo.GetRef().Number));
using (MemoryStream ms = new MemoryStream())
{
dotnetImg.Save(ms, ImageFormat.Tiff);
Images.Add(ms.ToArray());
}
}
}
}
}
I tried these links for a solution
Extract images using iTextSharp
Extract Image from a particular page in PDF
and was able to extract the raw image bytes using PdfReader.GetStreamBytesRaw() function but "Parameter not valid "exception always occurs at the point where System.Drawing.Image.FromStream(memory stream) is called.
I also checked this link "Parameter is not valid" exception from System.Drawing.Image.FromStream() method , but could not find anything helpful.
Please help
The JPXDecode filter corresponds to JPEG 2000 compression, which is not supported by .net framework. This other question in SO may help: JPEG 2000 support in C#.NET
Using FreeImage.dll solved the problem. The code is as follows
using FreeImageAPI;
using System.Drawing.Imaging;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
...
imagecount = 0;
PdfReader pdf = new PdfReader(currfilename);
PdfReaderContentParser parser = new PdfReaderContentParser(pdf);
ImageRender listener = new ImageRender();
for (int i = 1; i <= pdf.NumberOfPages; i++)
{
try
{
parser.ProcessContent(i, listener);//calls RenderImage() at this point
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
if (listener.Images.Count > 0)
{
for (int j = 0; (j < listener.Images.Count); ++j)
{
string imgpath = Environment.CurrentDirectory.ToString() + "\\Image" + imagecount + ".bmp";
// create a memory stream
MemoryStream imageStream = new MemoryStream(listener.Images[j]);
// create a FIBITMAP from that stream
FIBITMAP dib = FreeImage.LoadFromStream(imageStream);
if (dib.IsNull) continue;
//turn it into a normal Bitmap
Bitmap bitmap = FreeImage.GetBitmap(dib);
bitmap.Save(imgpath);
//unload the FIBITMAP
FreeImage.UnloadEx(ref dib);
bitmap.Dispose();
System.Drawing.Image img = System.Drawing.Image.FromFile(imgpath);
}
public void RenderImage(ImageRenderInfo renderInfo)
{
PdfImageObject image = renderInfo.GetImage();
if (renderInfo.GetRef() != null && image != null)
{
byte[] tempImage = image.GetImageAsBytes();
ImageNames.Add(string.Format("0}.bmp",renderInfo.GetRef().Number));
Images.Add(tempImage);
}
}
I followed the instructions given here to add FreeImage .Net to solution

Post Image from Blackberry WebWorks SDK Camera to PHP File Server

I am using Blackberry webworks i want to upload image from camera to php webserver i am getting image in uri and it is displaying correctly but i dont know how to upload image to server please help.
file uri
file://dir/image name
i am using this code from blackberry webworks camera api
function takePicture() {
try {
blackberry.media.camera.takePicture(photoTaken, closedCB, errorCB);
} catch (e) {
//alert("Error in supported: " + e);
}
}
function successCB(filePath) {
var file = "file://" + filePath;
$("#myfileCam").val(file);
$("#imgPic").show();
$("#imgPic").attr("src", file);
}
function photoTaken(filePath) {
var img = new Image();
img.src = "file://" + filePath;
img.width = Math.round(screen.width / 2);
document.getElementById("path").appendChild(img);
var html = "<input type='file' name='myfile' id='myfile' value='file://" + filepath + "' />";
document.getElementById("fileup").innerHTML = html;
//$("#fileup").html();
$("#myfileCam").val("file://" + filePath);
}
function closedCB() {
// alert("Camera closed event");
}
function errorCB(e) {
alert("Error occured: " + e);
}
FileConnection fc= (FileConnection)Connector.open(filePath);
InputStream is=fc.openInputStream();
byte[] ReimgData = IOUtilities.streamToBytes(is);
EncodedImage encode_image =EncodedImage.createEncodedImage(ReimgData, 0, (int)fc.fileSize());
JPEGEncodedImage encoder=JPEGEncodedImage.encode(encode_image.getBitmap(),50);
byte[] array=encoder.getData();
// Decodes the image represented by this EncodedImage and returns a Bitmap
int length=array.length;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(length);
Base64OutputStream base64OutputStream = new Base64OutputStream( byteArrayOutputStream );
try{
base64OutputStream.write( array, 0, length );
base64OutputStream.flush();
base64OutputStream.close();
}
catch (IOException ioe){
//Dialog.alert("Error in encodeBase64() : "+ioe.toString());
System.out.println("Error in encodeBase64() : "+ioe.toString());
}
data = Base64InputStream.decode(byteArrayOutputStream.toString());
Use Phonegap for Blackberry Webworks I had the same problem and i resolved using this api.
http://docs.phonegap.com/en/1.5.0/phonegap_file_file.md.html#FileTransfer here everything you need.
The only thing you need to do is to put the phonegap jar file in ext folder and call for permissions en config.xml adding this feature (phonegap), and that it.
I hope this work to you, it worked to me.

Why is part of the image cut out when taking a picture with this code on Blackberry?

When I take a picture on the simulator (Haven't tried a device yet) the result is only less than half of the image and the rest is gray. Does anyone know why?
Thanks
listener = new FileSystemJournalListener()
{
private long _lastUSN;
public void fileJournalChanged()
{
long nextUSN = FileSystemJournal.getNextUSN();
FileSystemJournalEntry entry = FileSystemJournal.getEntry(nextUSN - 1);
nextUSN++;
switch (entry.getEvent()) {
case FileSystemJournalEntry.FILE_ADDED:
try
{
FileConnection fconn = (FileConnection)Connector.open("file://" +entry.getPath());
if(fconn.exists())
{
InputStream input = null;
input = fconn.openInputStream();
byte[] data = new byte[(int) fconn.fileSize() + 1000];
input.read(data);
rawImage = data;
pic = Bitmap.createBitmapFromBytes(data, 0, -1, 1);
if(input != null)
{
input.close();
}
Bitmap[] images = new Bitmap[1];
images[0] = pic;
//labels[1] = "Label for image 2";
// tooltips[1] = "Tooltip for image 2";
// labels[2] = "Label for image 2";
// tooltips[2] = "Tooltip for image 2";
ScrollEntry[] entries = new ScrollEntry[images.length];
entries[0] = new ScrollEntry(images[0], "", "");
PictureScrollField pictureScrollField = new PictureScrollField(175, 131);
pictureScrollField.setData(entries, 0);
pictureScrollField.setHighlightStyle(HighlightStyle.ILLUMINATE_WITH_SHRINK_LENS);
// pictureScrollField.setHighlightBorderColor(Color.BLUE);
pictureScrollField.setBackground(BackgroundFactory.createSolidTransparentBackground(Color.BLACK, 150));
insert(pictureScrollField, 1);
picTaken = true;
EventInjector.KeyEvent inject = new EventInjector.KeyEvent(EventInjector.KeyEvent.KEY_DOWN, Characters.ESCAPE, 0, 50);
inject.post();
inject.post();
}
break;
}
catch (Exception e)
{
// TODO Auto-generated catch block
Dialog.alert(e.toString());
}
//either a picture was taken or a picture was added to the BlackBerry device
case FileSystemJournalEntry.FILE_DELETED:
//a picture was removed from the BlackBerry device;
break;
}
input.read(data) only reads some amount of data, not all of it. If you want to read the whole file, use IOUtilities.streamToBytes(input); instead, like this:
byte[] data = IOUtilities.streamToBytes(input);
byte[] data = new byte[(int) fconn.fileSize() + 1000];
...
pic = Bitmap.createBitmapFromBytes(data, 0, -1, 1);
I think data now contains last wrong 1000 bytes, try changing to:
byte[] data = new byte[(int) fconn.fileSize()];
I faced the same problem. Just use:
synchronized(UiApplication.getEventLock()) {
//your code here
}

Resources