Emoji support in imagick - imagick

I want to print the captions imported from facebook/instagram in an image and save it. I want to do this using imagick library with php as I am creating the base image using imagick. The normal text prints properly but the emojis that are imported do not get printed as emoji's. Can anyone suggest how emojis can be printed using imagick.
What I have tried:
$eachpageimg = new Imagick ();
$eachpageimg->setResolution ( 300 , 300 );
$eachpageimg->newImage (1050, 1260 , 'rgb(255,255,255)');
$eachpageimg->setImageUnits(imagick::RESOLUTION_PIXELSPERINCH);
$eachpageimg->setImageFormat ('jpeg');
$eachpageimg->setImageCompressionQuality(100);
$draw = new ImagickDraw();
$pixel = new ImagickPixel( 'rgb(255, 255, 255)' );
$pixel->setColorValue(Imagick::COLOR_ALPHA, .8);
$draw->setStrokeColor('rgb(0,0,0)');
$draw->setFillColor ('rgb(0,0,0)');
$draw->setFont ("ROBOTO-REGULAR");
$draw->setFontSize (70);
$xpos = 10;
$ypos = 200;
$eachpageimg->annotateImage($draw, $xpos, $ypos, 0, "Gshdh😚😎😑😚🤠");
$filename = 'saved.jpg';
// SAVE FINAL page image
file_put_contents ($filename, $eachpageimg);

The font you are using needs to have the emojis in them. This can be checked by just editing a word or web page with that font set.
However:
"Gshdh😚😎😑😚🤠"
Those look very much like a mucked up character set rather than emoji. I strongly suspect that you are saving some data in a character set that doesn't support emoji (i.e. most non-UTF) character sets.
Exactly where that has happened will need to be something you discover yourself.

Related

Writing Macro in ImageJ to open, change color, adjust brightness and resave microscope images

I'm trying to write a code in Image J that will:
Open all images in separate windows that contains "488" within a folder
Use look up tables to convert images to green and RGB color From ImageJ, the commands are: run("Green"); and run("RGB Color");
Adjust the brightness and contrast with defined values for Min and Max (same values for each image).
I know that the code for that is:
//run("Brightness/Contrast..."); setMinAndMax(value min, value max); run("Apply LUT");
Save each image in the same, original folder , in Tiff and with the same name but finishing with "processed".
I have no experience with Java and am very bad with coding. I tried to piece something together using code I found on stackoverflow and on the ImageJ website, but kept getting error codes. Any help is much appreciated!
I don't know if you still need it, but here is an example.
output_dir = "C:/Users/test/"
input_dir = "C:/Users/test/"
list = getFileList(input_dir);
listlength = list.length;
setBatchMode(true);
for (z = 0; z < listlength; z++){
if(endsWith(list[z], 'tif')==true ){
if(list[z].contains("488")){
title = list[z];
end = lengthOf(title)-4;
out_path = output_dir + substring(title,0,end) + "_processed.tif";
open(input_dir + title);
//add all the functions you want
run("Brightness/Contrast...");
setMinAndMax(1, 15);
run("Apply LUT");
saveAs("tif", "" + out_path + "");
close();
};
run("Close All");
}
}
setBatchMode(false);
I think it contains all the things you need. It opens all the images (in specific folder) that ends with tif and contains 488. I didn't completely understand what you want to do with each photo, so I just added your functions. But you probably won't have problems with adding more/different since you can get them with macro recorder.
And the code is written to open tif files. If you have tiff just be cerful that you change that and also change -4 to -5.

iText Image and transparency

I'm trying to add a PNG image to an existing pdf, but the transparency is converted to black color.
PdfReader reader = new PdfReader(pdfPath);
File f = new File(pdfPath);
String result = f.getParent() + File.separator + UUID.randomUUID().toString() + ".pdf";
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(result));
Image image = Image.getInstance(ImageIO.read(new File(imagePath)), null);
PdfImage stream = new PdfImage(image, null, null);
PdfIndirectObject ref = stamper.getWriter().addToBody(stream);
image.setDirectReference(ref.getIndirectReference());
image.setAbsolutePosition(30, 300);
PdfContentByte canvas = stamper.getOverContent(1);
canvas.addImage(image);
stamper.close();
reader.close();
How can I keep transparency?
First this: I am violating the policy at iText Software by answering this question. You are using an old version of iText, and the policy dictates that voluntary support on iText 5 or earlier has stopped. You should either use iText 7, or you should get a support contract if you still want support for an old iText version.
However, I am curious. I want to know where you found this clunky code (or why you decided to write this code):
Image image = Image.getInstance(ImageIO.read(new File(imagePath)), null);
PdfImage stream = new PdfImage(image, null, null);
PdfIndirectObject ref = stamper.getWriter().addToBody(stream);
image.setDirectReference(ref.getIndirectReference());
image.setAbsolutePosition(30, 300);
PdfContentByte canvas = stamper.getOverContent(1);
canvas.addImage(image);
You don't need ImageIO and you don't need to create a PdfImage, nor do you need to add that image to the body of a PDF file. The code you are using is code specialists would use for a very particular purpose. If you know that particular purpose, please explain.
If adding an image at an absolute position is all you want to do (that's a general purpose, not a particular purpose), your code should be as simple as this:
Image image = Image.getInstance(imagePath);
image.setAbsolutePosition(30, 300);
PdfContentByte canvas = stamper.getOverContent(1);
canvas.addImage(image);
In this case, you don't have to worry about the image mask; iText will take care of that for you.
Please also explain why you're using an outdated version of iText instead of iText 7. If you want your application to be future-proof, you should upgrade to iText 7 now (to avoid wasting time later).

Using Chinese fonts in TCPDF and FPDI. Encoding problems

I am writing a script that generates Chinese character worksheets (so students can generate and practice writing)
The script is passed a 15 character string from a form in index.php.
The string is then exploded into an array of 15 elements (each a Chinese character).
The problem arises when I want to use the Write() function to populate the file with these characters, I've used the input to pick appropiate images without any problems but now it's the encoding of the fonts that gives me a hard time.
PS. I need to use a cursive/handwritten font as default 'print' fonts are not suitable for handwriting practice.
Ideally I would like to use HDZB_36.TTF or Sharp Regular Script Font
See the code below as well as images of errors I get with some different fonts.
<?php
header('Content-Type: text/html; charset=utf-8');
// linking TCPDF and FPDI libraries
require_once('tcpdf/tcpdf.php');
require_once('fpdi/fpdi.php');
// First retrieve a 15 chinese charcters long string from POST form in index.php
$hanzi = $_POST["hanzi"];
// Explode the hanzi into a 15 items array
function mb_str_split($hanzi){
return preg_split('/(?<!^)(?!$)/u', $hanzi);
}
$charlist = mb_str_split($hanzi);
// Define starting y positions of each line of the grid
$yPos1 = 10.71;
$yPos2 = 17.94;
// Creating new page with PDF as a background
$pdf = new FPDI();
$background = $pdf->setSourceFile('images/worksheet_template1.pdf');
$tplIdx = $pdf->importPage(1);
$pdf->AddPage();
$pdf->useTemplate($tplIdx, 0, 0, 210, 285, false);
/*
This is where the problem starts, I can manage to display latin characters using helvetica
but when I use any of the chinese fonts (usually encoded as GB2312 or BIG5) it fails.
With some larger (ex. stsong) fonts I get a browser error saying: No data received ERR_EMPTY_RESPONSE (Image 1)
With font 'htst3' the characters appeared upside down and were full of artifacts (Image 2).
With font HDZB_36 the characters were not rendered at all.
Other fonts will result in all of the chars displayed as '?' (Image 3)
*/
$fontname = TCPDF_FONTS::addTTFfont('ukai.ttf', 'TrueTypeUnicode', '', 64);
$pdf->SetFont('ukai','', 20);
for ($i = 0; $i <= 14; $i++){
// Generating path of the stroke order image (that works fine)
$sImgPath = "images/x-s.png";
$sImgPath = str_ireplace('x', $charlist[$i], $sImgPath);
// Stroke order image
$pdf->Image($sImgPath, '14', $yPos1, '','5');
// Here we will populate grid of the worksheet with chinese characters as TEXT
$pdf->SetXY(12.4,$yPos2);
$pdf->SetTextColor(0, 0, 0);
$pdf->Write(0, $charlist[$i], '', false);
$pdf->SetXY(24.2,$yPos2);
$pdf->SetTextColor(192,192,192);
$pdf->Write(0, $charlist[$i], '', false);
// Increase the y pos values so the next run of for() will draw in another line
$yPos1 = $yPos1+17.83;
$yPos2 = $yPos2+17.78;
}
ob_clean();
$pdf->Output('worksheet.pdf', 'I');
?>
Just a suggestion:
The file you generate worksheet.pdfshould perhaps have the same encoding as your letters.
The PDF should have the appropriate encoding, see: https://stackoverflow.com/a/10656899/1933185

Arabic font in Web UI and itextsharp

I'm not able to find a reason why my MVC 3 web site shows arabic font correctly and my pdf not.
I use a bliss font in my web site;
#font-face {
font-family: 'blissregular';
src: url('/Fonts/blissregular-webfont.eot');
src: url('/Fonts/blissregular-webfont.eot?#iefix') format('embedded-opentype'),
url('/Fonts/blissregular-webfont.ttf') format('truetype');
font-weight: normal;
font-style: normal;}
All working fine.
After that I want to create the pdf of the output but arabic fonts does not appears.
I've googled and understand that the font must have the arabic character to show up correctly. I've changed to arial font (that contains arabic character) and... pdf worked.
So... How is possible that with bliss font (that does NOT have arabic characters) I see arabic font in web site?
I'm really confused....
thanks a lot to everybody!
For every character your browser encounters it looks for a matching glyph in the current font. If the font doesn't have that glyph it looks for any fallback fonts to see if they have that glyph. Ultimately every browser has a core set of default fonts that are the ultimate fallback. When you specify the font Bliss but use Arabic characters you are probably just seeing your browser's fallback fonts.
PDFs don't work that way. If you say something is using font XYZ then it will try to render it using that font or fail.
The easiest way probably is to just add a font to your CSS that supports those characters.
.myclass{font-family: blissregular, Arial}
If that doesn't work you might need to inject the fonts manually. (Actually, I'm not 100% certain the iText support #font-face, either.) iText has a helper class that can figure things out for you that Bruno talks about it here but unfortunately the C# link isn't working anymore. It's very simple, you just create an instance of the FontSelector class, call AddFont in the order that you want characters to be looked up up in and then pass a string to the Process() method which spits back a Phrase that you can add. Below is basic sample code that shows this off. I apologize for my sample text, I'm English-native so I just searched for something to use, I hope I didn't mangle it or get it backwards.
You'll need to jump through a couple of extra hoops when processing the HTML but you should be able to work it out, hopefully.
//Sample string. I apologize, this is from a Google search so I hope it isn't backward
var testString = "يوم الاثنين \"monday\" in Arabic";
var outputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
//Standard PDF setup
using (var fs = new FileStream(outputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
//This is a font that I know *does not* support Arabic characters, substitute with your own font if you don't have it
var gishaFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "gisha.ttf");
var gishaBaseFont = BaseFont.CreateFont(gishaFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
var gishaFont = new iTextSharp.text.Font(gishaBaseFont, 20);
//Add our test string using just a normal font, this *will not* display the Arabic characters
doc.Add(new Phrase(testString, gishaFont));
//This is a font that I know *does* support Arabic characters
var arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "ARIALUNI.TTF");
var arialBaseFont = BaseFont.CreateFont(arialFontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
var arialFont = new iTextSharp.text.Font(arialBaseFont, 20);
//Create our font selector specifying our most specific font first
var Sel = new FontSelector();
Sel.AddFont(gishaFont);
Sel.AddFont(arialFont);
//Have the font selector process our text into a series of chunks wrapped in a phrase
var newPhrase = Sel.Process(testString);
//Add the phrase, this will display both characters
doc.Add(newPhrase);
//Clean up
doc.Close();
}
}
}

Photoshop javascript save error 8800

In my javascript, in Windows 7, Photoshop CS2 & Photoshop CS5, it throws an error:
Error 8800: General Photoshop error occurred. This functionality may not be available in this version of Photoshop.
- Could not save a copy as "C:...\wcb-010B-11Y.jpg" because the file could not be found.
Line: 458
-> docRef.saveAs( saveFile, jpgSaveOptions, true, Extension.LOWERCASE );
here is a summary of the code to save the image:
var selectedSaveDir = "~/Desktop/";
var sFileNamePreFix = "wcb-";
var docRef = app.activeDocument;
var docName = app.activeDocument.name;
var docNewName = docName.substr( 0, docName.length - 4 ); // strip file extension
var sNewDocName = sFileNamePreFix + docNewName + ".jpg"
var sNewFileName = selectedSaveDir + sNewDocName;
//alert( "sNewFileName = " + sNewFileName ); // test to verify correct location
var saveFile = new File(sNewFileName);
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.quality = 12;
docRef.saveAs(saveFile, jpgSaveOptions, true, Extension.LOWERCASE);
In Windows XP, this script works very well in CS2 with no problems.... just in Windows 7 is where this issue occurs using CS2 or CS5.
The problem seems to be similar to : Photoshop Javascript scripting saving and closing document
But I don't know his OS.
I've added the "alert(" and confirmed the save folder & name is correct and can be saved to, but same issue.
Could it be a UAC issue in Windows 7 ? and how do you Fix it ? I've turned off all UAC settings (I think I did it correctly), but it still occurs.
Any Help ?
You missed out " var docRef = app.activeDocument;" (which i've added); but apart from that, in CS2 the script saves out a jpeg to the desktop (wcb-text test.jpg). It's obvious, but have you made sure the image is flattened or doesn't contain any information that cannot be stored in a jpeg - like paths for example.
Try forcing a flatten before saving
//flatten the image
docRef.flatten();
Another thing to try is to save out the file to another directory. I know that long file names (especially with spaces in) can cause problems - I think there's a limit to 300 characters in the file path.
I just found that, in new versions of PS this particular path variable gives the error 8800:
var selectedSaveDir = "~/Desktop/";
Use full path instead and use apostrophes instead of quotes:
var selectedSaveDir = 'C:/Users/yourname/Desktop/';

Resources