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
Related
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 ?
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");
}
I want to serialize a RenderImage as a text string so that I can java a Jason-like file with some fields (Name, Date, Photo).
I would like to use
String s = String.format("%s:%s,%s:%s,%:%s",
"name", my_name,
"date", date,
"photo", someFunctionToGenerateAStringForTheImage(RenderedImage));
And save s to a file.
Currently, I am using this:
public static byte[] imageToByteArray(RenderedImage img) {
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
ImageIO.write(img, "png", out);
out.flush();
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
And I call it as such:
String imageAsString =new String(Util.imageToByteArray(post.getImage()));
I deserialize the strings using the following function:
public static RenderedImage byteArrayToImage(byte[] bytes) {
try (ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
return ImageIO.read(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Thus I call it as such byteArrayToImage(imageAsString.getBytes());
Unfortunately, this approach is not working, the objects produced aren't the same... I would like to it using a String.format because my code is much more complex and full of recursive calls, so I want the simplest way of achieving this.
What can you recommend me?
You can try using Data URL:
public static String imageToDataUrl(RenderedImage img) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try {
ImageIO.write(img, "png", bytes);
} catch (IOException e) {
throw new RuntimeException(e);
}
String data = DatatypeConverter.printBase64Binary(bytes.toByteArray()),
//proper data url format
dataUrl = "data:image/png;base64," + data;
return dataUrl;
}
And to deserialise:
public static RenderedImage dataUrlToImage(String dataUrl) {
String data = dataUrl.substring(dataUrl.indexOf(',')+1);
byte[] bytes = DatatypeConverter.parseBase64Binary(data);
try (ByteArrayInputStream in = new ByteArrayInputStream(bytes)) {
return ImageIO.read(in);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
Create class
class MyImage {
String name;
Date date;
String photo;
}
and use any json lib, for example GSON:
String s = new GSON.toJson(myImage).replace('{'}.replace{'}');
MyImage myImage = new GSON.fromJson("{"+s+"}", MyImage.class);
Update:
if you have problem with serialization image try to use:
String s = new String(utf8Bytes, "UTF8");
byte[] utf8Bytes = original.getBytes("UTF8");
instead of
String s = new String(utf8Bytes);
byte[] defaultBytes = original.getBytes();
I am new to android.The Image is store in server by Base64 format. so how can i get it from server to My Project and set to my ImageView using Json Object.
Please Help me
Any help will be Appappreciated
Try this:
Convert Url to byte[] first:
byte[] bitmapdata = getByteArrayImage(url);
Method:
private byte[] getByteArrayImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
Now convert the byte[] to bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);
And set your bitmap to your ImageView:
img= (ImageView) findViewById(R.id.imgView);
img.setImageBitmap(bitmap );
I found easy solution:
byte[] img = Base64.decode(userHeader.GetImage(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
imageww.setImageBitmap(getCircleBitmap(bitmap));
Using Apache's commons-io-2.5 lib we can get using this function IOUtils.toByteArray(is)
public static String getByteArrayFromURL(final String url) {
String base64Image = "";
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> result = executor.submit(new Callable<String>() {
public String call() throws Exception {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
return Base64.encodeToString(IOUtils.toByteArray(is), Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
});
try {
base64Image = result.get();
} catch (Exception exception) {
exception.printStackTrace();
}
return base64Image;
}
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();
}
}
}