making and storing a barcode image from a barcode URL (Barcode4J) - java

I'm not very familiar with barcodes or barcode4j. I have a URL of the barcode and need to connect to that URL, stream it in order to make an image from it, then store that image somewhere on the file system.
does anyone have experience doing this with Barcode4J?
below i make the url...
private BarcodeRequestBean barCodeProcess(ResponseWithBarCode barCode)throws Exception
{
//hard coding bar code encoding and font size time being
String barCodeNum = ((ResponseWithBarCode)barCode).getBarCodeNumber();
logger.info("Please check below barcode generating parameters if generation failed:");
logger.info("BarCode Number = " + barCodeNum);
if (StringUtils.isEmpty(barCodeNum)||(barCodeNum==null))
{
throw new Exception("ResponseWithBarCode returned invalid barCodeNumber value!");
}
BarcodeRequestBean barbean = new BarcodeRequestBean();
//set bar code number
barbean.setMsg(barCodeNum); //reference number
//set default value
barbean.setType(config.getString("barcode.encoding")); //ex:code128
barbean.setHumanReadableSize(config.getString("barcode.font.size")); //ex:3pt
barbean.setWideFactor(config.getString("barcode.wide.factor")); //wide factor: 2
barbean.setFormat(config.getString("barcode.file.format")); //file format: png
barbean.setHeight(config.getString("barcode.height")); //heigh:1cm
barbean.setModuleWidth(config.getString("barcode.module.width")); //Module width: 0.15mm
return barbean;
}
I have a string of the url as such:
String genbc = barCodeProcess(barCode).toURL();

Perhaps you should learn to think more clear about your work.
Solving this issue, from what I understand, has nothing to do with bar codes. You have an image, that is available through an URL, and you must download it. That problem has been viewed many times on stack overflow and you would have found it if you did the search: "java downloading an image". It was the first result that came up for me in google.

Related

Rendering big Post Script file with Ghost4J in Java

i made a Java application whose purpose is to offer a Print Preview for PS files.
My program uses Ghostscript and Ghost4J to load the Post Script file and produces a list of Images (one for each page) using the SimpleRenderer.render method. Then using a simple JList i show only the image corresponding to the page the user selected in JList.
This worked fine until a really big PS file occurred, causing an OutOfMemoryError when executing the code
PSDocument pdocument = new PSDocument(new File(filename));
I know that is possibile to read a file a little at a time using InputStreams, the problem is that i can't think of a way to connect the bytes that i read with the actual pages of the document.
Example, i tried to read from PS file 100 MB at a time
int buffer_size = 100000000;
byte[] buffer = new byte[buffer_size];
FileInputStream partial = new FileInputStream(filename);
partial.read(buffer, 0, buffer_size);
document.load(new ByteArrayInputStream(buffer));
SimpleRenderer renderer = new SimpleRenderer();
//how many pages do i have to read?
List<Image> images = renderer.render(document, firstpage ??, lastpage ??);
Am i missing some Ghost4J functionality to read partially a file?
Or has someone other suggestions / approaches about how to solve this problem in different ways?
I am really struggling
I found out I can use Ghost4J Core API to retrieve from a Post Script file a reduced set of pages as Images.
Ghostscript gs = Ghostscript.getInstance();
String[] gsArgs = new String[9];
gsArgs[0] = "-dQUIET";
gsArgs[1] = "-dNOPAUSE";
gsArgs[2] = "-dBATCH";
gsArgs[3] = "-dSAFER";
gsArgs[4] = "-sDEVICE=display";
gsArgs[5] = "-sDisplayHandle=0";
gsArgs[6] = "-dDisplayFormat=16#804";
gsArgs[7] = "-sPageList="+firstPage+"-"+lastPage;
gsArgs[8] = "-f"+filename;
//create display callback (capture display output pages as images)
ImageWriterDisplayCallback displayCallback = new ImageWriterDisplayCallback();
//set display callback
gs.setDisplayCallback(displayCallback);
//run PostScript (also works with PDF) and exit interpreter
try {
gs.initialize(gsArgs);
gs.exit();
Ghostscript.deleteInstance();
} catch (GhostscriptException e) {
System.out.println("ERROR: " + e.getMessage());
e.printStackTrace();
}
return displayCallback.getImages(); //return List<Images>
This solve the problem of rendering page as images in the preview.
However, i could not find a way to use Ghost4J to know total number of pages of PS file (in case the file is too big for opening it with Document.load()).
So, i am still here needing some help

Write continuous stream to file flutter/dart

I have a radio live streaming link which I need to record when the user clicks the start button. Then once the user clicks stop I need to save the stream into a file.
I was able to successfully do this using java by reading the data as a byte array and writing a simple while loop stating as long as the data is not null write the byte into an array and when it is null then write the byte array to a file. Below I can provide a snippet of the code I have used in Java.
URL url = new URL(radioStream);
inputStreamRecording = url.openStream();
fileOutputStreamRecording = new FileOutputStream(OutputSourceStream + "/temp.mp3");
recordingBuffer = inputStreamRecording.read();
while (recordingBuffer > -1) {
fileOutputStreamRecording.write(recordingBuffer);
recordingBuffer = inputStreamRecording.read();
}
However, I am at a loss on how to do it in dart/flutter and cannot find any sort of example on this. So my question is how would I convert the Java code I have above into something I could use in Flutter. I am assuming I would use Future but how would you stop a future during the recording on a click event? Any help would be appreciated. Thank you in advance!
var out = File('out.dat').openWrite();
var ss = Stream.periodic(3.seconds, (i) {
print('generating event #$i');
return 'line $i\n'.codeUnits;
})
.listen(out.add);
Future.delayed(15.seconds, () {
print('calling ss.cancel');
ss.cancel();
});
This answer is very close to what I was looking for in case anyone else is trying to find this answer. All credit goes to #pskink!

Java saving large images in threads - IP camera broken images

After clicking a button in my app, it creates new normal Thread and start downloading large image and saving it to file. Everything is going well, but when i click button more than once it's going without errors and when i try to view these images they're bugged like they re overwriting themself.
I don't have any idea how to debug it.
localPath = today + "/" + productCode + "/" + this.placeId; //Unique
/* ... */
private void productSave(String productCode, int whichCamera, boolean isError) {
for (int i = position; i < lastCamera; i++) {
Date dateSave = new Date();
path = localPath + "/" + dateFormat.format(dateSave) + "_" + (i + 1) + ".jpg";
try {
BufferedImage imageOld = ImageIO.read(new URL(this.camerasUrlsToSave[i]));
ImageIO.write(imageOld, "jpg", new File(rootPath + "/" + path));
ComDb.getInstance().saveProduct(productCode, this.placeId, path, dateSave);
} catch (IOException ex) {
result = false;
}
}
}
EDIT: path is 100% unique (different folders with product code). And it shoudn't be problem with image from camera - I can open 10 cards i dont see image bugs
EDIT2: Can it be something like downloading Img bufor? Cause all images are downloaded from the same IP. Or maybe its problem with bufferedimg memory leaks. Need idea how to repair it.
EDIT3: I found that if i open 5 cards in web browser with my camera address like : blah.blah.some.ip/GetImage.cgi?CH=0 They're loading one after the other, not all at once. But, i dont see bugged images when downloading ends.
EDIT4: I tried to reproduce this bug in web browser, if i try to open link in ff and in IE. IE prints "getImage busy". When I try ff and chrome i got broken images. So i have to do sth like queue or disable button ...
EDIT5: My temporary solution: synchronized function productSave. Images from second click will be saved few seconds later.
http://oi57.tinypic.com/ofrrn.jpg!
One from saved Images
First action of the click event for the button should be to disable the button and maybe change the text to "In process". Last action should be to re-enable the button and restore the text.
This answer is a guess as you have not given full code, issue could be with variable i - where is it from?
Or could be same file name is being reused, mnake sure that is nto the case by getting unique file name from a seperate function something like this:
if dateFormat is only to minute or second, same file name might be used for 2 images use this API of java.io.File to get a unique name
http://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile%28java.lang.String,%20java.lang.String,%20java.io.File%29
public static File createTempFile(String prefix,
String suffix,
File directory)
//you can pass extn as jpg
public File getFileName(File localPath ,Date dateSave, int i, String extn){
File fileUniqe = File.createTempFile(dateSave + "_" + (i+1), extn, localPath );
return fileUniqe,
}

Change id3 tag version programatically (pref java)

I need a way to change id3 tag version of mp3 files to some id3v2.x programatically, preferably using java though anything that works is better than nothing. Bonus points if it converts the existing tag so that already existing data isn't destroyed, rather than creating a new tag entirely.
Edit: Jaudiotagger worked, thanks. Sadly I had to restrict it to mp3 files and only saving data contained in previous tags if they were id3. I decided to convert the tag to ID3v2.3 since windows explorer can't handle v2.4, and it was a bit tricky since the program was a bit confused about whether to use the copy constructor or the conversion constructor.
MP3File mf = null;
try {
mf = (MP3File)AudioFileIO.read(new File(pathToMp3File));
} catch (Exception e) {}
ID3v23Tag tag;
if (mf.hasID3v2Tag()) tag = new ID3v23Tag(mf.getID3v2TagAsv24());
else if (mf.hasID3v1Tag()) tag = new ID3v23Tag(mf.getID3v1Tag());
else tag = new ID3v23Tag();
My application must be able to read id3v1 or id3v11, but shall only write v23, so I needed a little bit longer piece of code:
AudioFile mf;
Tag mTagsInFile;
...
mf = ... // open audio file the usual way
...
mTagsInFile = mf.getTag();
if (mTagsInFile == null)
{
//contrary to getTag(), getTagOrCreateAndSetDefault() ignores id3v1 tags
mTagsInFile = mf.getTagOrCreateAndSetDefault();
}
// mp3 id3v1 and id3v11 are suboptimal, convert to id3v23
if (mf instanceof MP3File)
{
MP3File mf3 = (MP3File) mf;
if (mf3.hasID3v1Tag() && !mf3.hasID3v2Tag())
{
// convert ID3v1 tag to ID3v23
mTagsInFile = new ID3v23Tag(mf3.getID3v1Tag());
mf3.setID3v1Tag(null); // remove v1 tags
mf3.setTag(mTagsInFile); // add v2 tags
}
}
Basically we have to know that getTagOrCreateAndSetDefault() and similar unfortunately ignores id3v1, so we first have to call getTag(), and only if this fails, we call the mentioned function.
Additionally, the code must also deal with flac and mp4, so we make sure to do our conversion only with mp3 files.
Finally there is a bug in JaudioTagger. You may replace this line
String genre = "(" + genreId + ") " + GenreTypes.getInstanceOf().getValueForId(genreId);
in "ID3v24Tag.java" with this one
String genre = GenreTypes.getInstanceOf().getValueForId(genreId);
Otherwise genre 12 from idv1 will get "(12) Other" which later is converted to "Other Other" and this is not what we would expect. Maybe someone has a more elegant solution.
You can use different libraries for this purpose, for example this or this.

Textscreen in Codename One, how to read text file?

I want to add a help screen to my Codename One App.
As the text is longer as other strings, I would like put it in a separate file and add it to the app-package.
How do I do this? Where do I put the text file, and how can I easily read it in one go into a string?
(I already know how to put the string into a text area inside a form)
In the Codename One Designer go to the data section and add a file.
You can just add the text there and fetch it using myResFile.getData("name");.
You can also store the file within the src directory and get it using Display.getInstance().getResourceAsStream("/filename.txt");
I prefer to have the text file in the filesystem instead of the resource editor, because I can just edit the text with the IDE. The method getResourceAsStream is the first part of the solution. The second part is to load the text in one go. There was no support for this in J2ME, you needed to read, handle buffers etc. yourself. Fortunately there is a utility method in codename one. So my working method now looks like this:
final String HelpTextFile = "/helptext.txt";
...
InputStream in = Display.getInstance().getResourceAsStream(
Form.class, HelpTextFile);
if (in != null){
try {
text = com.codename1.io.Util.readToString(in);
in.close();
} catch (IOException ex) {
System.out.println(ex);
text = "Read Error";
}
}
The following code worked for me.
//Gets a file system storage instance
FileSystemStorage inst = FileSystemStorage.getInstance();
//Gets CN1 home`
final String homePath = inst.getAppHomePath();
final char sep = inst.getFileSystemSeparator();
// Getting input stream of the file
InputStream is = inst.openInputStream(homePath + sep + "MyText.txt");
// CN1 Util class, readInputStream() returns byte array
byte[] b = Util.readInputStream(is);
String myString = new String(b);

Categories