If we search image to qr code, there are many websites which converts image to qr code online.
But how can I do this in java?
I am using the following code for converting text to qr code:-
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class MyQr {
public static void createQR(String data, String path,
String charset, Map hashMap,
int height, int width)
throws WriterException, IOException
{
BitMatrix matrix = new MultiFormatWriter().encode(
new String(data.getBytes(charset), charset),
BarcodeFormat.QR_CODE, width, height);
MatrixToImageWriter.writeToFile(
matrix,
path.substring(path.lastIndexOf('.') + 1),
new File(path));
}
public static void main(String[] args)
throws WriterException, IOException,
NotFoundException
{
String data = "TEXT IN QR CODE";
String path = "image.png";
String charset = "UTF-8";
Map<EncodeHintType, ErrorCorrectionLevel> hashMap
= new HashMap<EncodeHintType,
ErrorCorrectionLevel>();
hashMap.put(EncodeHintType.ERROR_CORRECTION,
ErrorCorrectionLevel.L);
createQR(data, path, charset, hashMap, 200, 200);
}
}
But how to encode a image in qr code?
Images are too big to be embedded into QR codes (with the exception of tiny icons). So instead, the image is put on a publicly accessible server and the URL of the image is embedded in the QR code.
Thus you need access to a server that can fulfill this. That's probably the bigger part of what you are about to implement.
Otherwise, it's straight-forward:
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class MyQr {
/**
* Uploads the image to a server and returns to image URL.
* #param imagePath path to the image
* #return image URL
*/
public static URL uploadImage(String imagePath)
{
// implement a solution to put an image on a public server
try {
return new URL("https://yourserver/some_path/image.jpg");
} catch (MalformedURLException e) {
throw new RuntimeException(e);
}
}
public static void createQR(String payloadImagePath, String qrCodeImagePath,
Map<EncodeHintType, ?> hints, int height, int width)
throws WriterException, IOException
{
URL imageURL = uploadImage(payloadImagePath);
BitMatrix matrix = new MultiFormatWriter().encode(
imageURL.toString(), BarcodeFormat.QR_CODE, width, height, hints);
String imageFormat = qrCodeImagePath.substring(qrCodeImagePath.lastIndexOf('.') + 1);
MatrixToImageWriter.writeToPath(matrix, imageFormat, Path.of(qrCodeImagePath));
}
public static void main(String[] args)
throws WriterException, IOException
{
String payloadImagePath = "embed_this.jpg";
String qrCodeImagePath = "qrcode.png";
Map<EncodeHintType, ErrorCorrectionLevel> hints = new HashMap<>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
createQR(payloadImagePath, qrCodeImagePath, hints, 200, 200);
}
}
BTW: The below code (from your code sample) is non-sense. At best, it creates a copy of the string, which is unnecessary. At worst, it corrupts all characters not supported by charset. I don't think you intended either one.
new String(data.getBytes(charset), charset)
I assume that you mean that you want to add an image (e.g. logo) to the QR Code.
This is generally done by overlaying a small image on top of the QR Code, usually in the center. QR Codes are still readable when a small portion is obscured, especially in the center.
You can use MatrixToImageWriter.toBufferedImage(matrix) to get a BufferedImage containing the QR Code image, and then use Java image methods to overlay the image. See, for example, overlay images in java
Related
I want to generate QR code with some text using JAVA like this.
please check this image. This is how I want to generate my QR code.
(with user name and event name text)
This is my code and this generate only (QR) code, (not any additional text). If anyone know how to generate QR code with text please help me.
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class Create_QR {
public static void main(String[] args) {
try {
String qrCodeData = "This is the text";
String filePath = "C:\\Users\\Nirmalw\\Desktop\\Projects\\QR\\test\\test_img\\my_QR.png";
String charset = "UTF-8"; // or "ISO-8859-1"
Map < EncodeHintType, ErrorCorrectionLevel > hintMap = new HashMap < EncodeHintType, ErrorCorrectionLevel > ();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
BitMatrix matrix = new MultiFormatWriter().encode(new String(qrCodeData.getBytes(charset), charset),
BarcodeFormat.QR_CODE, 500, 500, hintMap);
MatrixToImageWriter.writeToFile (matrix, filePath.substring(filePath.lastIndexOf('.') + 1), new File(filePath));
System.out.println("QR Code created successfully!");
} catch (Exception e) {
System.err.println(e);
}
}
}
You can generate a QR code with text in Java using Free Spire.Barcode for Java API. First, download the API's jar from this link or install it from Maven Repository:
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.barcode.free</artifactId>
<version>5.1.1</version>
</dependency>
</dependencies>
Next, refer to the following code sample:
import com.spire.barcode.BarCodeGenerator;
import com.spire.barcode.BarCodeType;
import com.spire.barcode.BarcodeSettings;
import com.spire.barcode.QRCodeECL;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class GenerateQRCode {
public static void main(String []args) throws IOException {
//Instantiate a BarcodeSettings object
BarcodeSettings settings = new BarcodeSettings();
//Set barcode type
settings.setType(BarCodeType.QR_Code);
//Set barcode data
String data = "https://stackoverflow.com/";
settings.setData(data);
//Set barcode module width
settings.setX(2);
//Set error correction level
settings.setQRCodeECL(QRCodeECL.M);
//Set top text
settings.setTopText("User Name");
//Set bottom text
settings.setBottomText("Event Name");
//Set text visibility
settings.setShowText(false);
settings.setShowTopText(true);
settings.setShowBottomText(true);
//Set border visibility
settings.hasBorder(false);
//Instantiate a BarCodeGenerator object based on the specific settings
BarCodeGenerator barCodeGenerator = new BarCodeGenerator(settings);
//Generate QR code image
BufferedImage bufferedImage = barCodeGenerator.generateImage();
//save the image to a .png file
ImageIO.write(bufferedImage,"png",new File("QR_Code.png"));
}
}
The following is the generated QR code image with text:
To generate a QR code in Java, we need to use a third-party library named ZXing (Zebra Crossing). It is a popular API that allows us to process with QR code. With the help of the library, we can easily generate and read the QR code. Before moving towards the Java program, we need to add the ZXing library to the project. We can download it from the official site.
zxing core-3.3.0.jar
zxing javase-3.3.0.jar
After downloading, add it to the classpath. Or add the following dependency in pom.xml file.
<dependencies>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
</dependencies>
Let's create a Java program that generates a QR code.
GenerateQrCode.java
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
public class GenerateQRCode
{
//static function that creates QR Code
public static void generateQRcode(String data, String path, String charset, Map map, int h, int w) throws WriterException, IOException
{
//the BitMatrix class represents the 2D matrix of bits
//MultiFormatWriter is a factory class that finds the appropriate Writer subclass for the BarcodeFormat requested and encodes the barcode with the supplied contents.
BitMatrix matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, w, h);
MatrixToImageWriter.writeToFile(matrix, path.substring(path.lastIndexOf('.') + 1), new File(path));
}
//main() method
public static void main(String args[]) throws WriterException, IOException, NotFoundException
{
//data that we want to store in the QR code
String str= "THE HABIT OF PERSISTENCE IS THE HABIT OF VICTORY.";
//path where we want to get QR Code
String path = "C:\\Users\\Anubhav\\Desktop\\QRDemo\\Quote.png";
//Encoding charset to be used
String charset = "UTF-8";
Map<EncodeHintType, ErrorCorrectionLevel> hashMap = new HashMap<EncodeHintType, ErrorCorrectionLevel>();
//generates QR code with Low level(L) error correction capability
hashMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
//invoking the user-defined method that creates the QR code
generateQRcode(str, path, charset, hashMap, 200, 200);//increase or decrease height and width accodingly
//prints if the QR code is generated
System.out.println("QR Code created successfully.");
}
}
In a Java backend server application I want to decode a QR code embedded into a PDF file using the zxing library.
I adapted the example from https://gist.github.com/JoelGeraci-Datalogics/dd9e214d4c584d61f5b1 to work with the pdfbox library as follows:
ReadBarcodeFromPDF.java
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
public class ReadBarcodeFromPDF {
private static final List<String> urlList = Arrays.asList(
"http://dev.datalogics.com/cookbook/forms/ReadBarcodeImage_QRCode.pdf",
"http://dev.datalogics.com/cookbook/forms/ReadBarcodeImage_DataMatrix.pdf",
"http://dev.datalogics.com/cookbook/forms/ReadBarcodeImage_PDF417.pdf"
);
public static void main(String[] args) throws Exception {
for (String url : urlList) {
readCode(url);
}
}
private static String readCode(String url) throws MalformedURLException, IOException, NotFoundException {
URLConnection connection = new URL(url).openConnection();
connection.connect();
try (InputStream inputStream = connection.getInputStream()) {
try (PDDocument document = PDDocument.load(inputStream)) {
PDFRenderer pdfRenderer = new PDFRenderer(document);
BufferedImage bufferedImage = pdfRenderer.renderImageWithDPI(0, 300, ImageType.BINARY);
LuminanceSource luminanceSource = new BufferedImageLuminanceSource(bufferedImage);
HybridBinarizer hybridBinarizer = new HybridBinarizer(luminanceSource);
BinaryBitmap bitmap = new BinaryBitmap(hybridBinarizer);
MultiFormatReader reader = new MultiFormatReader();
Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
hints.put(DecodeHintType.POSSIBLE_FORMATS, Arrays.asList(
BarcodeFormat.QR_CODE,
BarcodeFormat.DATA_MATRIX,
BarcodeFormat.PDF_417
));
hints.put(DecodeHintType.PURE_BARCODE, Boolean.FALSE);
hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
reader.setHints(hints);
Result result = reader.decodeWithState(bitmap);
return result.getText();
}
}
}
}
The example is supposed to recognize codes from PDF documents with different code types:
QR Code: http://dev.datalogics.com/cookbook/forms/ReadBarcodeImage_QRCode.pdf
Data Matrix: http://dev.datalogics.com/cookbook/forms/ReadBarcodeImage_DataMatrix.pdf
PDF417: http://dev.datalogics.com/cookbook/forms/ReadBarcodeImage_PDF417.pdf
But it fact it recognizes only the PDF417. The QR Code (in which I am interested) and the data matrix (in which I am not interested) are not recognized.
The output is
com.google.zxing.NotFoundException
com.google.zxing.NotFoundException
11/15/2010 Tony Blue
I also tried
Different arguments in line
pdfRenderer.renderImageWithDPI(0, 300, ImageType.BINARY);
Different values for dpi (2nd argument) between 100 and 300
All available values for imageType (3rd argument)
Newest version of the library (3.5.0)
pom.xml
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.26</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
Your code works if one removes
hints.put(DecodeHintType.PURE_BARCODE, Boolean.FALSE);
I suspect that ZXIng only checks whether there is an entry for the key and not its value. The javadoc mentions "Doesn't matter what it maps to; use Boolean.TRUE."
I want to create pptx file having linked-Video in slides using Apache-poi.
I got one example in Apache-Examples code
poi-4.1.2\src\scratchpad\testcases\org\apache\poi\hslf\model\TestMovieShape.
Using this example I can able to create .ppt file but it's not creating .pptx file.
Also using this example media-controls are not visible.
Only a few lines needed to be changed opposed to the embedded video case.
The video URI is not a real URI, but simply a relative .mp4 filename in the same directory. Although I haven't tested it, absolute file URIs should also work.
I haven't implemented the frame extraction, as it's mentioned in the embedded example - so either look for an archived version of xuggler or find a different library to extract the preview image.
Tested with Powerpoint 2016 / POI 5.0.0-Snapshot.
import org.apache.poi.openxml4j.opc.PackagePart;
import org.apache.poi.openxml4j.opc.PackageRelationship;
import org.apache.poi.openxml4j.opc.TargetMode;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.xslf.usermodel.XMLSlideShow;
import org.apache.poi.xslf.usermodel.XSLFPictureData;
import org.apache.poi.xslf.usermodel.XSLFPictureShape;
import org.apache.poi.xslf.usermodel.XSLFSlide;
import org.apache.xmlbeans.XmlCursor;
import org.openxmlformats.schemas.drawingml.x2006.main.CTHyperlink;
import org.openxmlformats.schemas.presentationml.x2006.main.*;
import javax.xml.namespace.QName;
import java.awt.*;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import static org.apache.poi.openxml4j.opc.PackageRelationshipTypes.CORE_PROPERTIES_ECMA376_NS;
public class LinkVideoToPptx {
public static void main(String[] args) throws IOException, URISyntaxException {
XMLSlideShow pptx = new XMLSlideShow();
String videoFileName = "file_example_MP4_640_3MG.mp4";
XSLFSlide slide1 = pptx.createSlide();
PackagePart pp = slide1.getPackagePart();
URI mp4uri = new URI("./"+videoFileName);
PackageRelationship prsEmbed1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.microsoft.com/office/2007/relationships/media");
PackageRelationship prsExec1 = pp.addRelationship(mp4uri, TargetMode.EXTERNAL, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video");
File previewJpg = new File("preview.jpg");
XSLFPictureData snap = pptx.addPicture(previewJpg, PictureData.PictureType.JPEG);
XSLFPictureShape pic1 = slide1.createPicture(snap);
pic1.setAnchor(new Rectangle(100, 100, 500, 400));
CTPicture xpic1 = (CTPicture)pic1.getXmlObject();
CTHyperlink link1 = xpic1.getNvPicPr().getCNvPr().addNewHlinkClick();
link1.setId("");
link1.setAction("ppaction://media");
CTApplicationNonVisualDrawingProps nvPr = xpic1.getNvPicPr().getNvPr();
nvPr.addNewVideoFile().setLink(prsExec1.getId());
CTExtension ext = nvPr.addNewExtLst().addNewExt();
ext.setUri("{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}");
String p14Ns = "http://schemas.microsoft.com/office/powerpoint/2010/main";
XmlCursor cur = ext.newCursor();
cur.toEndToken();
cur.beginElement(new QName(p14Ns, "media", "p14"));
cur.insertNamespace("p14", p14Ns);
cur.insertAttributeWithValue(new QName(CORE_PROPERTIES_ECMA376_NS, "link"), prsEmbed1.getId());
cur.dispose();
CTSlide xslide = slide1.getXmlObject();
CTTimeNodeList ctnl;
if (!xslide.isSetTiming()) {
CTTLCommonTimeNodeData ctn = xslide.addNewTiming().addNewTnLst().addNewPar().addNewCTn();
ctn.setDur(STTLTimeIndefinite.INDEFINITE);
ctn.setRestart(STTLTimeNodeRestartType.NEVER);
ctn.setNodeType(STTLTimeNodeType.TM_ROOT);
ctnl = ctn.addNewChildTnLst();
} else {
ctnl = xslide.getTiming().getTnLst().getParArray(0).getCTn().getChildTnLst();
}
CTTLCommonMediaNodeData cmedia = ctnl.addNewVideo().addNewCMediaNode();
cmedia.setVol(80000);
CTTLCommonTimeNodeData ctn = cmedia.addNewCTn();
ctn.setFill(STTLTimeNodeFillType.HOLD);
ctn.setDisplay(false);
ctn.addNewStCondLst().addNewCond().setDelay(STTLTimeIndefinite.INDEFINITE);
cmedia.addNewTgtEl().addNewSpTgt().setSpid(""+pic1.getShapeId());
try (FileOutputStream fos = new FileOutputStream("mp4test-poi.pptx")) {
pptx.write(fos);
}
}
}
I need to read a image in java ad convert to byte array for postgreSQL.
I have tried the following code, is it ok?
import java.nio.file.Files;
import java.nio.file.Path;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.Arrays;
public class ConvertImage {
public static void main(String[] args) throws IOException {
Path filepath = Paths.get("image.jpg");
byte[] byteContent = Files.readAllBytes(filepath);
System.out.println(Arrays.toString(byteContent));
}
}
And how to do the way back, form byte array to image?
You can create a ByteArrayInputStream from the byte array and supply it to ImageIO as follows:
ByteArrayInputStream is = new ByteArrayInputStream( byteContent );
BufferedImage image = ImageIO.read( is );
I have a problem when using LWJGL and STB TrueType in IntelliJ.
When I now try to create a bitmap and put everything in Main ('Code 1' below), everything works fine.
As soon as I try to split this up and create an OpenGL context (If I split it up without creating an OpenGL context it works fine as well), the loaded font gets corrupted somehow and either the program crashes with an ACCESS_VIOLATION or runs without generating the bitmap. You can see the broken code as 'Code 2' below.
The wrong behaviour though only occurs when running with the java run arguments, that IntelliJ uses - either via Intellij Run or via Console.
It doesnt occur dont happen when building into a JAR and running this.
The problematic argument is the following. If this one is missing in the console, it runs.
-javaagent:<INTELLIJ_HOME>\lib\idea_rt.jar=52850:<INTELLIJ_HOME>\bin
I have read here that the idea_rt.jar file "is needed to provide graceful shutdown/exit/stacktrace features" and therefore I do not want to disable it in IntelliJ.
NOTE: In the broken code ('Code 2' below) you will notice an 'unnecessary' line
ByteBuffer data2 = loadByteBufferFromResource("/fonts/arial.ttf"); which simulates loading multiple fonts. If I only load one font, everything works fine.
You will also notice the OpenGL context creation in code 2, which also seems to be a cause of the problem (as I described above)
Code 1 (works)
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL;
import org.lwjgl.stb.STBTTFontinfo;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.Map;
import static org.lwjgl.glfw.GLFW.glfwCreateWindow;
import static org.lwjgl.glfw.GLFW.glfwDefaultWindowHints;
import static org.lwjgl.glfw.GLFW.glfwInit;
import static org.lwjgl.glfw.GLFW.glfwMakeContextCurrent;
import static org.lwjgl.stb.STBTruetype.stbtt_GetCodepointBitmap;
import static org.lwjgl.stb.STBTruetype.stbtt_InitFont;
public class STBTTExampleOnlyMain {
private static ByteBuffer loadByteBufferFromResource(String resource) throws IOException {
try(InputStream stream = STBTTExampleOnlyMain .class.getResourceAsStream(resource)) {
byte[] bytes = stream.readAllBytes();
ByteBuffer buffer = BufferUtils.createByteBuffer(bytes.length);
buffer.put(bytes);
buffer.flip();
return buffer;
}
}
public static void main(String[] args) throws IOException {
ByteBuffer data = loadByteBufferFromResource("/fonts/arial.ttf");
ByteBuffer data2 = loadByteBufferFromResource("/fonts/arial.ttf");
STBTTFontinfo font = STBTTFontinfo.create();
stbtt_InitFont(font, data);
IntBuffer bufWidth = BufferUtils.createIntBuffer(1);
IntBuffer bufHeight = BufferUtils.createIntBuffer(1);
ByteBuffer bitmap = stbtt_GetCodepointBitmap(font, 0, 1, 'a', bufWidth, bufHeight, null, null);
System.out.println(bitmap);
}
}
Code 2 (broken)
import org.lwjgl.BufferUtils;
import org.lwjgl.opengl.GL;
import org.lwjgl.stb.STBTTFontinfo;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.util.HashMap;
import java.util.Map;
import static org.lwjgl.glfw.GLFW.glfwCreateWindow;
import static org.lwjgl.glfw.GLFW.glfwDefaultWindowHints;
import static org.lwjgl.glfw.GLFW.glfwInit;
import static org.lwjgl.glfw.GLFW.glfwMakeContextCurrent;
import static org.lwjgl.stb.STBTruetype.stbtt_GetCodepointBitmap;
import static org.lwjgl.stb.STBTruetype.stbtt_InitFont;
public class STBTTExample {
private static final Map<Integer, STBTTFontinfo> fontMap = new HashMap<>();
private static ByteBuffer loadByteBufferFromResource(String resource) throws IOException {
try(InputStream stream = STBTTExample.class.getResourceAsStream(resource)) {
byte[] bytes = stream.readAllBytes();
ByteBuffer buffer = BufferUtils.createByteBuffer(bytes.length);
buffer.put(bytes);
buffer.flip();
return buffer;
}
}
private static void initFont() throws IOException {
ByteBuffer data = loadByteBufferFromResource("/fonts/arial.ttf");
ByteBuffer data2 = loadByteBufferFromResource("/fonts/arial.ttf");
STBTTFontinfo font = STBTTFontinfo.create();
stbtt_InitFont(font, data);
fontMap.put(0, font);
}
public static void main(String[] args) throws IOException {
initFont();
glfwInit();
glfwDefaultWindowHints();
long windowHandle = glfwCreateWindow(800, 600, "Test", 0, 0);
glfwMakeContextCurrent(windowHandle);
GL.createCapabilities();
IntBuffer bufWidth = BufferUtils.createIntBuffer(1);
IntBuffer bufHeight = BufferUtils.createIntBuffer(1);
ByteBuffer bitmap = stbtt_GetCodepointBitmap(fontMap.get(0), 0, 1, 'a', bufWidth, bufHeight, null, null);
System.out.println(bitmap);
}
}
How can fix the problem of not being able to run the program out of IntelliJ when working with text rendering?
Am I maybe misunderstanding the STBTT library and actually can't work with fonts this way?
Any help would be appreciated to understand what is wrong and fix this.
I have asked the question in the LWJGL forum and got it solved.
The STBTTFontinfo object contains metadata only. The actual font data is NOT copied from the ByteBuffer you pass to stbtt_InitFont. Only its memory address is copied and the font data is accessed via that pointer when necessary. The segfault you're seeing happens because you don't store a reference to the ByteBuffer anywhere, it is GCed/deallocated by the time you try to use the font. An easy fix would be to change your Font class to also store the ByteBuffer.
You can look at the post here.