how to create an emoji image with graphics2d and google noto color font - graphics2d

I wrote a java program to render an emoji and create a local image file with it. To do that I downloaded Google's "Noto Color Emoji" font from google website.
This is mi code:
package com.test;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class Test {
public static void main(String[] args) throws IOException {
String string = "ЁЯШД";
BufferedImage image;
Font font = null;
try {
font = Font.createFont(Font.TRUETYPE_FONT, new FileInputStream("/home/sandra/.fonts/NotoColorEmoji.ttf"));
} catch (FontFormatException e) {
e.printStackTrace();
}
image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = image.createGraphics();
g2.setFont(font);
g2.drawString(string, 0, g2.getFontMetrics().getAscent());
g2.dispose();
File f = new File("image.png");
if (!f.exists()) {
if (!f.createNewFile()) {
System.err.println("Can't create image file.");
}
}
try {
ImageIO.write(image, "png", f);
} catch (IOException e) {
e.printStackTrace();
}
}
}
I tried to run it in both mac and linux (ubuntu) and the output in both cases is a black square.
Am I missing anything obvious? I also tried these commands mentioned at the end of this post (https://github.com/notwaldorf/ama/issues/53) but there is no difference on the output image.
I would appreciate any help on this as I'm quite new on emoji display.
Thanks in advance,
Sandra

Change:
image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
to:
image = new BufferedImage(100, 100, BufferedImage.TYPE_INT_ARGB);
It needs TYPE_INT_ARGB.
And add this before drawString():
g2.setPaint(Color.WHITE)

Related

How can I include native code in Flutter to display a KML Layer on Google Map?

I've been looking into running native code in my Flutter app to display a KML Layer on my Google Map and while I do have the app running native code (at least on Android), I am having difficulty with getting the KML stuff to work.
I have created a MethodChannel in my Flutter class to run the native code and this works fine. Please see below.
// Run java code for KML Campus Map Overlay
Future<void> _showCampusMap() async {
const platform = MethodChannel('uk.ac.manchestermaps/kmlLayer');
try {
final campusMapOverlay =
await platform.invokeMethod('retrieveFileFromUrl');
print(campusMapOverlay);
} on PlatformException catch (error) {
print(error);
}
}
I am taking some code that I used on the Android only pre-alpha version of the app, so I know it works, but I have 4 errors.
In my MainActivity java file,I have these package.
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import org.xmlpull.v1.XmlPullParserException;
import android.os.AsyncTask;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
and the MainActivity class consists of this.
public class MainActivity extends FlutterActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), "**<MY CHANNEL>**").setMethodCallHandler(new MethodCallHandler() {
#Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call.method.equals("retrieveFileFromUrl")) {
retrieveFileFromUrl();
result.success("KMLLayer Retrieved");
}
}
});
}
private void retrieveFileFromUrl() {
new DownloadKmlFile("**<REMOTE KML FILE>**")
.execute();
}
private class DownloadKmlFile extends AsyncTask<String, Void, byte[]> {
private final String mUrl;
public DownloadKmlFile(String url) {
mUrl = url;
}
protected byte[] doInBackground(String... params) {
try {
InputStream is = new URL(mUrl).openStream();
// Log.d(TAG, "doInBackground: " + mUrl.toString());
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(byte[] byteArr) {
try {
KmlLayer kmlLayer = new KmlLayer(mMap, new ByteArrayInputStream(byteArr), getApplicationContext());
kmlLayer.addLayerToMap();
// moveCameraToKml(kmlLayer);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Here are my errors
Running Gradle task 'assembleDebug'...
.....\MainActivity.java:73: error: cannot find symbol
KmlLayer kmlLayer = new KmlLayer(mMap, new ByteArrayInputStream(byteArr), getApplicationContext());
^
symbol: class KmlLayer
location: class MainActivity.DownloadKmlFile
.....\MainActivity.java:73: error: cannot find symbol
KmlLayer kmlLayer = new KmlLayer(mMap, new ByteArrayInputStream(byteArr), getApplicationContext());
^
symbol: class KmlLayer
location: class MainActivity.DownloadKmlFile
.....\MainActivity.java:73: error: cannot find symbol
KmlLayer kmlLayer = new KmlLayer(mMap, new ByteArrayInputStream(byteArr), getApplicationContext());
^
symbol: variable mMap
location: class MainActivity.DownloadKmlFile
3 errors
I have looked around, but can't find anything to help this this specific case as I don't think a lot of people are doing on it. I know KML support has been request for the google_maps_flutter package, but it seems to have gone quiet.
Any help with this would be very much appreciated, as it is pretty central to the app I am developing. Without this, the app is next to useless.
Thanks

Does google_maps_flutter or any other map plugin for flutter supports kml file for google maps?

I want to load kml files on google map in flutter. i can't find it on google _maps_flutter plugin. is there any other plugins which can do it in flutter?
It's been a month, so you may have figured this out, but hopefully, if you haven't this can help.
You can run native code in flutter, so if you can adapt this, it should work. You will need to create a Method Channel to run the native code with something like this.
// Run java code for KML Campus Map Overlay
Future<void> _showCampusMap() async {
const platform = MethodChannel(**<YOUR METHOD CHANNEL>**);
try {
final campusMapOverlay = await platform.invokeMethod('downloadKmlLayer');
print(campusMapOverlay);
} on PlatformException catch (error) {
print(error);
}
}
KML Layer code can be found in the URL below.
https://github.com/googlemaps/android-maps-utils/commit/d606fcde40467abb5fae2ba78b8562a2cd1c517b
Even though I have managed to get native code to work, with simply displaying some text, I haven't figured out how to get the KML Code to work yet.I think the problem lies in it not knowing what mMap is in the onPostExecute method, but it is very possible there is more than I do not know.
import java.io.Console;
import android.os.Bundle;
import io.flutter.app.FlutterActivity;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import org.xmlpull.v1.XmlPullParserException;
import android.os.AsyncTask;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class MainActivity extends FlutterActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), "**<YOUR METHOD CHANNEL>**").setMethodCallHandler(new MethodCallHandler() {
#Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
if (call.method.equals("retrieveFileFromUrl")) {
String KMLLayer = retrieveFileFromUrl();
result.success(KMLLayer);
}
}
});
}
private void retrieveFileFromUrl() {
new DownloadKmlFile("**<YOUR KML LAYER>**")
.execute();
}
private class DownloadKmlFile extends AsyncTask<String, Void, byte[]> {
private final String mUrl;
public DownloadKmlFile(String url) {
mUrl = url;
}
protected byte[] doInBackground(String... params) {
try {
InputStream is = new URL(mUrl).openStream();
// Log.d(TAG, "doInBackground: " + mUrl.toString());
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
buffer.write(data, 0, nRead);
}
buffer.flush();
return buffer.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(byte[] byteArr) {
try {
KmlLayer kmlLayer = new KmlLayer(mMap, new ByteArrayInputStream(byteArr), getApplicationContext());
kmlLayer.addLayerToMap();
// moveCameraToKml(kmlLayer);
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You can see here for a bit more details.
https://medium.com/47billion/creating-a-bridge-in-flutter-between-dart-and-native-code-in-java-or-objectivec-5f80fd0cd713
I hope gets you on the right path.
--------NOTE: only for android-------------
This solution won't work for iOS but there is a workaround for android, you can see the solution here in the medium article

Printing Issue for Unicode Devnagari Script in Java

I am creating a Java application in Hindi Language, National Language of India for which Devanagari Script is used.
I need to print some text in Hindi Language using Java Printing API.
But, I am facing some problems and can't able to figure out what is wrong!
Here is some screenshots that will state the problem.
When I show the text preview to user in my Java Application (Using Mangal Font):
But When I print the same using Java Printing Support (Using Mangal Font):
This is the problem. Notice some diacritics (matras) are shifted to the right!
However, MS Word seems to print it correctly using same Mangal Font:
And when I use Arial Unicode font in my Java Application, it works fine, too:
That's why, I am forced to use Arial Unicode Font! But, it's size is 22MB compared to 200KB size of Mangal Font. This makes my build (jar) very big in size. Application this big in size, cannot be used in production.
I don't even know where to start to know the cause of this problem. The shifted diacritics problem when printing Devnagari Unicode Text
Update:
Here is the code:
(Make sure both font files are on classpath! Both fonts are available on Windows named "Arial Unicode MS Regular" & "Mangal".)
import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.FontFormatException;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.IOException;
import javax.swing.Box;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class DevnagariTest {
private static Font createFont(String url) throws FontFormatException, IOException {
return Font.createFont(
Font.TRUETYPE_FONT,
DevnagariTest.class.getClassLoader().getResourceAsStream(url))
.deriveFont(30f);
}
private static JLabel getLabel(String text, Font font) {
JLabel label = new JLabel(text);
label.setFont(font);
return label;
}
public static void main(String[] args) throws FontFormatException, IOException {
Font mangal = createFont("mangal.ttf");
Font arial = createFont("ARIALUNI.TTF");
JFrame frame = new JFrame();
final Box box = Box.createVerticalBox();
box.add(getLabel("рдЧрдгреЗрд╢ рд╡рд╛рд░реНрдб рд░рдореЗрд╢ рд╕реБрд░реЗрд╢ рдкрдкреНрдкреВ рдкреГрдереНрд╡реА", mangal));
box.add(getLabel("рдЧрдгреЗрд╢ рд╡рд╛рд░реНрдб рд░рдореЗрд╢ рд╕реБрд░реЗрд╢ рдкрдкреНрдкреВ рдкреГрдереНрд╡реА", arial));
JButton print = new JButton("Print");
print.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
PrinterJob job = PrinterJob.getPrinterJob();
job.setPrintable(new Printable() {
#Override
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
if (pageIndex > 0) {
return NO_SUCH_PAGE;
}
Graphics2D g2 = (Graphics2D) graphics;
g2.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
box.printAll(g2);
g2.dispose();
return PAGE_EXISTS;
}
});
try {
job.print();
} catch (PrinterException ex) {
ex.printStackTrace();
}
}
});
frame.add(box, BorderLayout.CENTER);
frame.add(print, BorderLayout.SOUTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}

Setting an icon for a jFrame in Netbeans swing gui builder

I've been trying to set up a window in Netbean's GUI builder, without success. I've tried accessing the JFrame, from my main class as:
public void run(){
JFrame frame = new JFrame("Title of Frame");
frame.setIconImage(Toolkit.getDefaultToolkit().getImage("org/icon.png"));
}
Which creates a new frame apart from my main window with my icon.png. I'd like to know if there is some way to gain access to the JFrame that contains the rest of my UI elements, and set that icon.
I've also tried
new SearchAppUI().setIconImage(null);
which doesn't do anything of note.
Setting the icon directly:
JFrame.setIconImage("org/icon.png");
gives me the error, non-static method setIconImage(java.awt.Image) cannot be referenced from a static context.
Is there any way to set the main JFrame's icon from either Netbean's swing desinger preview, or from my run() method?
The OP is a bit dated but just for the record, try this:
frame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("org/icon.png")));
NVM, I found a solution on: http://www.youtube.com/watch?v=o_35iro4b7M
Describing how to set the icon and title of a jFrame. Basically, it requires
the libraries
import javax.swing.JFrame;
import java.awt.image.BufferedImage;
import java.io.File;
import java.awt.Image;
import javax.imageio.ImageIO;
I pretty much wanted to stick with using Netbean's guibuilder for now, at least for prototyping.
First of all. It's worth to read How to Make Frames.
You can use the following example.
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
public class FrameWithIcon extends JFrame {
public static void main(String[] args) {
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
FrameWithIcon myFrame = new FrameWithIcon();
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setTitle("Frame with Icon");
myFrame.setLayout(new BorderLayout());
myFrame.setIconImage(
loadImageIcon("org/icon.png").getImage());
Dimension size = new Dimension(250, 100);
JPanel panel = new JPanel();
panel.setPreferredSize(size);
myFrame.add(panel, BorderLayout.LINE_START);
myFrame.setVisible(true);
myFrame.pack();
}
});
} catch (InterruptedException ex) {
} catch (InvocationTargetException ex) {
}
}
/** Returns an ImageIcon, or null if the path was invalid. */
private static ImageIcon loadImageIcon(String path) {
URL imgURL = FrameWithIcon.class.getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
}

Converting a Jpeg into an uncompressed tiff image

I found this code on StackOverflow
import java.io.File;
import java.io.FileOutputStream;
import java.awt.image.RenderedImage;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import javax.media.jai.NullOpImage;
import javax.media.jai.OpImage;
import com.sun.media.jai.codec.SeekableStream;
import com.sun.media.jai.codec.FileSeekableStream;
import com.sun.media.jai.codec.TIFFDecodeParam;
import com.sun.media.jai.codec.ImageDecoder;
import com.sun.media.jai.codec.ImageCodec;
public class Main {
public static void main(String args[]) {
File file = new File("input.tif");
try {
SeekableStream s = new FileSeekableStream(file);
TIFFDecodeParam param = null;
ImageDecoder dec = ImageCodec.createImageDecoder("tiff", s, param);
RenderedImage op = new NullOpImage(dec.decodeAsRenderedImage(0),
null,
OpImage.OP_IO_BOUND,
null);
FileOutputStream fos = new FileOutputStream("output.jpg");
JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(fos);
jpeg.encode(op.getData());
fos.close();
}
catch (java.io.IOException ioe) {
System.out.println(ioe);
}
}
}
I have been trying to reverse this process - convert jpg to uncompressed tiff but but I cant seem to get it to work.
Any ideas?