How to display a barcode image in jsp - java

I'm using lowagie.text.jar to generate barcode. I need to display this generated barcode in jsp using spring MVC. Can someone help how to acheieve this?
class BarcodeController{
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
String strBarCode = request.getParameter(“barcode”);
byte[] pngImageData = null;
try {
Barcode39 code39ext = new Barcode39();
code39ext.setCode(strBarCode);
code39ext.setStartStopText(false);
code39ext.setExtended(true);
java.awt.Image rawImage = code39ext.createAwtImage(Color.BLACK, Color.WHITE);
BufferedImage outImage = new BufferedImage(rawImage.getWidth(null), rawImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
outImage.getGraphics().drawImage(rawImage, 0, 0, null);
ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
ImageIO.write(outImage, “png”, bytesOut);
bytesOut.flush();
pngImageData = bytesOut.toByteArray();
} catch (Exception e) {
e.printStackTrace();
}
if (pngImageData != null) {
response.setContentLength(pngImageData.length);
response.setContentType(“image/png”);
OutputStream out = response.getOutputStream();
out.write(pngImageData);
out.flush();
out.close();
}
}
}

Related

Get progress of readBytes in android

I've already seen
Is it possible to check progress of URLconnection.getInputStream()?
https://stackoverflow.com/a/20120451/5437621
I'm using the following code to download a file from internet:
try {
InputStream is = new URL(pdfUrl).openStream();
byte[] pdfData = readBytes(is);
return pdfData;
} catch (IOException e) {
e.printStackTrace();
return null;
}
public byte[] readBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
Is there any method I can get the progress of the file being downloaded ?
The answers I have seen are using a while loop but I don't understand how to use it in this case.
EDIT:
I'm using this in AsyncTask:
protected byte[] doInBackground(String... url) {
pdfUrl = url[0];
try {
InputStream is = new URL(pdfUrl).openStream();
DownloadBytes downloadData = readBytes(is);
byte[] pdfData = downloadData.getBytes();
progress = downloadData.getProgress();
return pdfData;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
How can I adjust publishProgress() in this method ?

How to let user download zip file using vaadin file downloader

I've followed this topic and it perfectly works. Here's the function to create resource for file downloader
private StreamResource createResource() {
return new StreamResource(new StreamSource() {
#Override
public InputStream getStream() {
String text = "My image";
BufferedImage bi = new BufferedImage(100, 30, BufferedImage.TYPE_3BYTE_BGR);
bi.getGraphics().drawChars(text.toCharArray(), 0, text.length(), 10, 20);
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ImageIO.write(bi, "png", bos);
return new ByteArrayInputStream(bos.toByteArray());
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}, "myImage.png");
}
but i don't know how to make it create a resource of zip file. Do i need to create many resources?. Thank you
Here's the solution that i figured out myself
private StreamResource createZipResource()
{
return new StreamResource(new StreamSource()
{
#Override
public InputStream getStream()
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try
{
ZipOutputStream out = new ZipOutputStream(byteArrayOutputStream);
for (int i = 0; i < listData.size(); i++)
{
if (listData.get(i).contains(".txt"))
{
out.putNextEntry(new ZipEntry(listData.get(i) + ".txt"));
}
else
{
out.write(listData.get(i).getBytes());
}
}
out.close();
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
}
catch (IOException e)
{
System.out.println("Problem writing ZIP file: " + e);
}
return null;
}
},"Filename.zip");
}

BufferedImage into Android bitmap

I've got a problem. I need to save a java BufferedImage object in an String. Convert this String on the Android application into Bitmap. How can I achieve this? Or maybe you can recommend me the other way to transfer image information in the String format.
public static String encodeToString(BufferedImage image, String type) {
String imageString = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ImageIO.write(image, type, bos);
byte[] imageBytes = bos.toByteArray();
imageString = Base64.getEncoder().encodeToString(imageBytes);
bos.close();
} catch (IOException e) {
log.error("Can't encode to String");
}
return imageString;
}
Base64 encoding and decoding of images using Java 8:
public static String imgToBase64String(final RenderedImage img, final String formatName) {
final ByteArrayOutputStream os = new ByteArrayOutputStream();
try {
ImageIO.write(img, formatName, Base64.getEncoder().wrap(os));
return os.toString(StandardCharsets.ISO_8859_1.name());
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
public static BufferedImage base64StringToImg(final String base64String) {
try {
return ImageIO.read(new ByteArrayInputStream(Base64.getDecoder().decode(base64String)));
} catch (final IOException ioe) {
throw new UncheckedIOException(ioe);
}
}
hope so will work,
enjoy your code:)

How to postpone doPost method?

In my servlet, I upload a file to a specific url, then call a method in a different class to grab that file online and alter it. The problem is that a lot of the time, there is a lot of data in the file and the dopost method finishes (and goes to the next page from the upload file submit form) before the file is fully altered. How do I prevent the do post method from going to the next page before my file is completely altered?
I want the Test.preFirstMethod() to finish before the page reloads and makes the download link. Test.preFirstMethod() takes in an excel file and modifies it using dynamic content from the internet.
public class Uploads extends HttpServlet {
private Object lock1 = new Object();
private static final long serialVersionUID = 1L;
private ServletFileUpload uploader = null;
public Thread tt = new Thread(new Runnable() {
public void run()
{
try {Test.preFirstMethod();
} catch (Exception e) {
e.printStackTrace();
}
}
});
int BUFFER_LENGTH = 4096;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String fileName="";
for (Part part : request.getParts()) {
InputStream is = request.getPart(part.getName()).getInputStream();
fileName = getFileName(part);
File f2 = new File(fileName);
FileOutputStream os = new FileOutputStream(System.getenv("OPENSHIFT_DATA_DIR") + "nn.xlsx");
byte[] bytes = new byte[BUFFER_LENGTH];
int read = 0;
while ((read = is.read(bytes, 0, BUFFER_LENGTH)) != -1) {
os.write(bytes, 0, read);
}
os.flush();
is.close();
fileName=fileName.substring(0,fileName.lastIndexOf("."))+"_ZillowAdded.xlsx";
try {
tt.start();
try { tt.join(); } catch (InterruptedException e) {
e.printStackTrace();
}
InputStream is2 = new FileInputStream(f2);
FileOutputStream os2 = new FileOutputStream(System.getenv("OPENSHIFT_DATA_DIR") + fileName);
while ((read = is2.read(bytes, 0, BUFFER_LENGTH)) != -1) {
os2.write(bytes, 0, read);
}
os2.flush();
is2.close();
os2.close();
} catch(Exception e) {e.printStackTrace();}
os.close();
}
if(!ServletFileUpload.isMultipartContent(request)){
throw new ServletException("Content type is not multipart/form-data");
}
response.setContentType("text/html");
out.write("<html><head></head><body>");
out.write("File "+fileName.substring(0,fileName.indexOf("_Zillow"))+ " uploaded successfully.");
out.write("<br>");
out.write("Download "+fileName+"");
out.write("</body></html>"); }

Buffered image as JPG over Tomcat Websocket to HTML 5 Canvas

Hey we want to send buffered images periodically over tomcat websockets into a canvas, kind of a livestream.
Server Code:
private static void broadcastImage(BufferedImage img) {
StreamInbound someClient;
byte[] arr = BufferedImageToByte(img);
ListIterator<StreamInbound> iter = clients.listIterator();
while (iter.hasNext()) {
someClient = (MessageInbound) iter.next();
try {
someClient.getWsOutbound().writeBinaryMessage(ByteBuffer.wrap(arr));
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static byte[] BufferedImageToByte(BufferedImage img) {
byte[] imageInBytes = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "jpg", baos);
baos.flush();
imageInBytes = baos.toByteArray();
baos.close();
} catch (Exception e) {
e.printStackTrace();
}
return imageInBytes;
}
the problem is how to pack this into the canvas.
Client Code:
ws = new WebSocket("ws://"+ location.host + "/carduinowebdroid/websocket");
ws.binaryType = "arraybuffer";
/** stuff **/
ws.onmessage = function(message){
if (message.data instanceof ArrayBuffer) {
streamHandleMessage(message);
}
}
function streamHandleMessage(message) {
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
/** what now? **/
}
Any help is greatly appreciated!
Do you really need a webSocket?
If not:
var can = document.getElementById('canvas');
var ctx = can.getContext('2d');
var img = new Image();
img.onload = function(){
can.width = img.width;
can.height = img.height;
ctx.drawImage(img, 0, 0, img.width, img.height);
}
img.src = 'img.jpg';
Otherwise have a look at this:
How can I create a canvas imageData array from an arrayBuffer representation of a JPG
or this
http://www.adobe.com/devnet/html5/articles/real-time-data-exchange-in-html5-with-websockets.html

Categories

Resources