texture is null while creating this from a Pixmap object in thread - java

try {
URL url = new URL(this.url);
InputStream in = new BufferedInputStream(url.openStream());
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n = 0;
while (-1 != (n = in.read(buf))) {
out.write(buf, 0, n);
}
out.close();
in.close();
byte[] response = out.toByteArray();
Pixmap pixmap = new Pixmap(response, 0, response.length);
texture = new Texture(pixmap); // <- here Im getting an exception
} catch (Exception e) {
// cause=NullPointerException
// pixmap was initialized successfully
}
All the code is working in thread.
Code works great in UI thread.
Any ideas?

I think you are not allowed to work with opengl in a thread different from the one where opengl context was created.
http://code.google.com/p/libgdx/wiki/ApplicationThreading

Related

Inconsistent output of zip functions between Python and Java methods

I'm integrating my system with external one.
My system is written in Java when external is writen in Python.
This system requires to compress body of request before sending it.
Below are functions used for compression:
def decompress(input_bytes):
bytes = input_bytes.encode('utf-8')
deflate_byte = base64.decodebytes(bytes)
output = zlib.decompress(deflate_byte)
out_str = output.decode('utf-8')
return out_str
def compress(input_str):
input_bytes = input_str.encode('utf-8')
compress = zlib.compress(input_bytes)
output_bytes = base64.encodebytes(compress)
out_str = output_bytes.decode('utf-8')
return out_str
I have developed code for compression/decompression in Java:
public byte[] compress(String str) {
byte[] data = str.getBytes(UTF_8);
Deflater deflater = new Deflater();
deflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
deflater.finish();
byte[] buffer = new byte[1024];
while (!deflater.finished()) {
int count = deflater.deflate(buffer); // returns the generated code... index
outputStream.write(buffer, 0, count);
}
try {
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
byte[] output = outputStream.toByteArray();
return Base64.decodeBase64(output);
}
#Override
public String decompress(byte[] data) {
Inflater inflater = new Inflater();
inflater.setInput(data);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
byte[] buffer = new byte[1024];
while (!inflater.finished()) {
int count = 0;
try {
count = inflater.inflate(buffer);
} catch (DataFormatException e) {
throw new RuntimeException(e);
}
outputStream.write(buffer, 0, count);
}
try {
outputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
byte[] output = outputStream.toByteArray();
return new String(output);
}
But the output of compression methods is incompatible:
Input:
test
Output of compression implemented in Python:
eJwrSS0uAQAEXQHB
Output of compression implemented in Java:
��>
I would be grateful for explanation of that difference and help how to get in Java solution that is equivalent to those Python methods.
Thank you in advance.

Java Android - JPEG Image rotation

I'm working on an application to capture images but I'd like to rotate a JPEG image before saving it, I already saw this link :
Android Rotate Picture before saving
This is what I'm doing right now.
ByteBuffer byteBuffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mImageFileName);
fileOutputStream.write(bytes);
} catch (IOException e) {
e.printStackTrace();
}
I tried this to rotate the image like this :
// Bytes array to bitmap and matrix rotation
Bitmap sourceBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Matrix m = new Matrix();
m.setRotate((float)90, sourceBitmap.getWidth(), sourceBitmap.getHeight());
Bitmap targetBitmap = Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), m, true);
// Bitmap to bytes array
int size = targetBitmap.getRowBytes() * targetBitmap.getHeight();
ByteBuffer targetByteBuffer = ByteBuffer.allocate(size);
targetBitmap.copyPixelsToBuffer(targetByteBuffer);
bytes = targetByteBuffer.array();
But when I look into the file into my gallery, I cannot read it, the image seems broken.
EDIT: Doesn't work on Android 7.1.1 :/ Any idea ? Can I do something similar for a video record?
You are Coverting Your Bitmap to bytes array,
Now You stop That way save Bitmap directly to File
Bitmap sourceBitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Matrix m = new Matrix();
m.setRotate((float)90, sourceBitmap.getWidth(), sourceBitmap.getHeight());
Bitmap rotatedBitmap= Bitmap.createBitmap(sourceBitmap, 0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight(), m, true);
// Save Bitmap directly to the file
String filename = "hello.jpg";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);
try {
FileOutputStream out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
This little change apparently did the trick ! Thanks Nikunj !
ByteBuffer byteBuffer = mImage.getPlanes()[0].getBuffer();
byte[] bytes = new byte[byteBuffer.remaining()];
byteBuffer.get(bytes);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Matrix matrix = new Matrix();
matrix.setRotate((float)90, bitmap.getWidth(), bitmap.getHeight());
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(mImageFileName);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}

Missing Bottom part of image using getResponse().getOutputStream().write

i got the image from post response
PostMethod post = new PostMethod(action);
HttpClient httpClient = createHttpClient();
........
httpClient.executeMethod(post);
try {
log.info("post successfully");
String contentType = post.getResponseHeader("Content-type").getValue();
int contentLength = (int) post.getResponseContentLength();
byte[] responseBody = FileUtils.convertInputStreamtoByteArray(post.getResponseBodyAsStream());
log.info("get response sucessfully : size "+ responseBody.length +" contentLength " + contentLength);
return new ReturnBean(null, responseBody,contentType,contentLength);
} catch (Exception e) {
log.error(e.getMessage());
log.error(e.getStackTrace());
e.printStackTrace();
throw new ResponseFailedException(e.getMessage());
}
this is how i convert inputstream to byte array.
public static byte[] convertInputStreamtoByteArray(InputStream is){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
byte[] buf = new byte[1024];
int i = 0;
while ((i = is.read(buf)) >= 0) {
baos.write(buf, 0, i);
}
is.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return baos.toByteArray();
}
this is how i return the image as a response.
byte[] imageSource = (byte[])returnStream.getBean();
log.info("imageSource " + imageSource.length);
getResponse().setContentType((String) returnStream.getBean2());
getResponse().setContentLength((Integer) returnStream.getBean3());
getResponse().getOutputStream().write(imageSource);
getResponse().getOutputStream().flush();
i was able to print out the image but im having a problem because the bottom part of it is missing . i checked the size of byte that i got and it is equal to the size of actual image.
when i used IOUtils.copyLarge(); instead of my method convertInputStreamtoByteArray
ServletOutputStream outputStream = getResponse().getOutputStream();
InputStream inputStream = (InputStream) returnStream.getBean();
IOUtils.copyLarge(inputStream , outputStream);
it works . i dont know what happen because i used it a while ago and it didnt work.

How to display image on a web-page from a url

Following is the snippet from a servlet that attempts to fetch image from the URL. I have fetched the bytes. Now how do I display the image on the webpage ?
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
URL url = new URL("https://abc/zhdhaG1z_bigger.jpeg");
InputStream stream = new BufferedInputStream(url.openStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte buf[] = new byte[1024];
int n = 0;
while(-1 != (n = stream.read(buf)) ) {
bos.write(buf, 0, n);
}
byte res[] = bos.toByteArray();
} finally {
out.close();
}
You Can Rewrite your code like this...see if this helps
public void doGet(HttpRequest request,HttpResponse response)throws ServletException{
response.setContentType("image/jpeg;charset=UTF-8");
response.addHeader("content-disposition", "inline;filename=Default.jpeg");
try {
URL url = new URL("https://abc/zhdhaG1z_bigger.jpeg");
InputStream stream = new BufferedInputStream(url.openStream());
ByteArrayOutputStream bos = new OutputStream();
byte buf[] = new byte[1024];
int n = 0;
while(-1 != (n = stream.read(buf)) ) {
bos.write(buf, 0, n);
}
}
catch(Exception e){
e.printStackTarce();
}
finally {
out.close();
}
}

read the file inside a jar but then can not delete it

my thread will read the class data from a jar file, another thread will modify or delete the jar file. the order is read first then delete, but it didn't work, seem that cann't release the resource after reading, how could I reach out?
InputStream is = null;
BufferedInputStream bis = null;
ByteArrayOutputStream baos = null;
try {
URL res = new URL(**file**);
is = res.openStream();
bis = new BufferedInputStream(is);
baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024 * 10];
int readBytes;
while ((readBytes = bis.read(bytes)) != -1) {
baos.write(bytes, 0, readBytes);
}
byte[] b = baos.toByteArray();
baos.close();
bis.close();
is.close();
return b;
} catch (Exception ex) {
throw ex;
}
the parameter "file" is a String like this "jar:file:///C:/Users/HJ16748/Desktop/test.jar!/com/services/plugin/test/Test.class"
Add a finally to your try catch block and close the resources there. Let two threads name be Read and Modify.
Inside Modify thread before deleting or modifying jar add line like this.
try{
System.out.println("Waiting for read to finish");
read.thread.join();
}catch(InterruptedException e){
System.out.println("not able to join");//oops catch
}
//codes to delete or modify jar
thread called with read is the Thread object
ZipFile zf = new ZipFile(entry);
file = file.replaceAll("\\\\", "/");
ZipEntry zipEntry = zf.getEntry(file);
BufferedInputStream bis = new BufferedInputStream(zf.getInputStream(zipEntry));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024 * 10];
int readBytes;
while ((readBytes = bis.read(bytes)) != -1) {
baos.write(bytes, 0, readBytes);
}
b = baos.toByteArray();
baos.close();
bis.close();
zf.close();

Categories

Resources