Convert /assets/image.png to byte[] - java

How to convert /assets/image.png to byte[] ?
I've tried like that (based on solution found on SO):
public void printimage(View view) {
AssetManager assetManager = getAssets();
InputStream inputStream = null;
try {
inputStream = assetManager.open("logo_print.png");
byte[] bytesLogo = IOUtils.toByteArray(inputStream);
int ret = printer.printImage(bytesLogo);
if (ret < 0) {
Toast(context, "printimage fail");
}
Toast(context, "image printed :)");
}
catch (IOException e){
Log.e("message: ", e.getMessage());
Toast(context, "printimage: convert image to Bytes fail");
}
}
printImage — is declared in package like this:
public class Cprinter {
public native int printImage(byte[] bytes);
}
But application crashes on print printimage(), error is "Native method not found: android.pt.Cprinter.printImage:([B)I"
I've converted byte to string (bytesLogo.toString()), every execution of this command returns different results: "[B#40d7c798", "[B#40d848e0", "[B#40d59ff0", & etc.
Purpose:
I have an android device with internal printer of receipts. Vendor has provided library (libfile.so) and sample source for developing own software for device. Printing Simple text is OK, but i have a troubles with printing of an Image (logo).
Here is the vendors` tiny documentation.
p.s:I'm newbie in Java.

Try this
InputStream inputStream = getAssets().open("logo_print.png");
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
byte file[] = output.toByteArray();
the byte array contains
1B 2A n ml mh converted data 1B 4A 00
1B 2A -- begin the block
n - printing mode
a) Q110 support 4 kinds of printing modes,as follow:
n=0x21: 24-point double-density;
n=0x20: 24-point single-density;
n=0x01: 8-point double-density;
n=0x00: 8-point single-density;
b) NXP only support n=0x21: 24-point double-density;
converted data
1B 4A 00 end the block and execute print (print start)
like wise
byte[0] = 0x1B;
byte[1] = 0x2A;
byte[2] = 0x21; // 24-point double-density;
and so on...

Copy your image into drawable folder. Then follow the steps:
Drawable drawable= getResources().getDrawable(R.drawable.image);
Type cast into BitmapDrawable,
Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
byte[] buffer= stream.toByteArray();
You can also try below code for asset folder image:
InputStream stream= null;
try {
stream = getAssets().open("fileName.extension");
byte[] fileBytes=new byte[stream.available()];
stream.read(fileBytes);
stream.close();
} catch (IOException e) {
e.printStackTrace();
}

This works for any type of file in the asset folder
InputStream is = getAssets().open("image.png");
byte[] fileBytes=new byte[is.available()];
is.read( fileBytes);
is.close();

Try this:
String filePath="file:///android_asset/logo_print.png";
Drawable d = Drawable.createFromPath(filePath);
And this.

Related

How to convert Bytes Array to a String in order to see it printed onto the console?

I am trying to convert a Byte Array to a String in order to be able to see this Vector/Array and analyse how these bytes are organized.
I'm using the code below to do it:
byte[] bytes = bos.toByteArray();
String msgDecode = new String(bytes); // trying to convert byte in String
System.out.println("Vetor de bytes [" + msgDecode + "]"); // Showing it
But it's not working. Why the code above it's no working?
It is worth mentioning that the Byte Array is being constructed according to this other code here:
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+UUID.randomUUID().toString()+"audio_record.3gp";
public byte[] convert(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
for (int readNum; (readNum = fis.read(b)) != -1; ) {
bos.write(b, 0, readNum);
}
byte[] bytes = bos.toByteArray();
return bytes;
}
The general idea is to record an audio with the smartphone and convert this audio file to a array of bytes. This String path is the path where the audio is being saved after recording. Then I use this path (that represents the audio file) and convert it to a byte array according to the code above.
More information you can find and help me here: How to solve this error: Android resource linking failed?
if you want to see value of bytes you can use as below:
Log.d("TAG", Arrays.toString(bytes));
What I'll try to do, based in what you guys said:
String decode = Arrays.toString(bytes);
Log.d("mytag", decode);
byte[] bytes = "ABCDEFG".getBytes();
System.out.println(new String(bytes)); // ABCDEFG
System.out.println(Arrays.toString(bytes)); // [65, 66, 67, 68, 69, 70, 71]

Bad Base - 64 Error when trying to send an Image

I am looking to share a screenshot of a page between two devices. The screenshot is stored in a Bitmap and then I am converting it to a byte array which is then converted to a String in Base 64. The String is then sent over to a handler which will display the image. After I try to decode the image it is giving me a: java.lang.IllegalArgumentException: bad base-64
I have already tried to send the images in different ways and have tried all the different Base 64 methods such as Base64.DEFAULT, URLSAFE, NOPADDING etc...
Here is where I am creating the screenshot and sending:
Bitmap b =
Screenshot.takescreenshotofRootView(MainActivity.imageView);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG,100,baos);
byte[] bytea = baos.toByteArray();
String temp = Base64.encodeToString(bytea, Base64.DEFAULT);
sendReceive.write(temp.getBytes());
This is where I am handling that data
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
switch (msg.what) {
case MESSAGE_READ:
MainActivity.imageView.setImageBitmap(bitm);
byte[] readBuff = (byte[]) msg.obj;
String tempMsg = new String(readBuff, 0, msg.arg1);
byte [] encodeByte = Base64.decode(tempMsg,Base64.URL_SAFE);
Bitmap bitms
= BitmapFactory.decodeByteArray(encodeByte,0,encodeByte.length);
MainActivity.imageView.setImageBitmap(bitms);
break;
}
return true;
}
});
You might be getting an OutOfMemoryError without realizing it, rendering your base64 string invalid. You should wrap your code with a try/catch block to see if that is happening. Here is an example in some code of mine:
String imageString = "";
try {
if (this.theBitmap != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
this.theBitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
imageString = Base64.encodeToString(bytes, Base64.DEFAULT);
}
}catch(OutOfMemoryError E){
Log.e("MyApp", "Out Of Memory error");
}

Serialization bytes are added to the servlet response outputstream, how to avoid it?

In doPost, return the bitmap
String mimeType = sc.getMimeType(filename);
// Set content type
resp.setContentType(mimeType);
// Set content size
File file = new File(filename);
resp.setContentLength((int)file.length());
// Open the file and output streams
FileInputStream in = new FileInputStream(file);
// Copy the contents of the file to the output stream
byte[] buf = new byte[1024];
int count = 0;
while ((count = in.read(buf)) >= 0) {
outStream.write(buf, 0, count);
}
Test with fiddler, 4 extra bytes are added to the header and 4 bytes are dropped from the bmp. They are AC ED 00 05, which is from serialization algorithm. It causes the bmp unrecognizable.
How to avoid these serialization bytes, when creating the output stream?

Encrypted Image Format For A Java Game

I am making a 2D game in Java for the PC and this game has data like sprites, sound effects, music, and text.
The problem is that I need to store it somehow.
For now I need to store my sprites in an encrypted format and I need my Java game To decrypt and load the encrypted images To bufferedimages to display them on my game.
I don't want to encapsulate everything into a single executable .jar or .exe file.
I need to make my images(Resources,Spritesheets) encrypted and secure because I don't want to the player to interfere with them or use them.
I can't use ZIP files even encrypted or protected ones by using some
sort of a Java library because Java have to export them first on the disc
before it uses it
I have searched many forums and I can't find a clear answer.
Depending upon what sort of encryption you had in mind - you can use ImageIO to write/read the image to Output and Input Streams, taking the resulting bytes and decrypt/encrypt.
To save the image, use ImageIO to write the Image to an OutputStream (for example a ByteArrayOutputStream ). From the bytes written, you can encrypt, and then save
ByteArrayOutputStream os = null;
OutputStream fos = null;
try{
os = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", os);
byte[] bytes = os.toByteArray();
encrypt(bytes);
fos = new FileOutputStream(outputfile);
fos.write(bytes);
}catch(IOException e){
e.printStackTrace();
}finally{
if ( fos != null ){try{fos.close();}catch(Exception e){}}
if ( os != null ){try{os.close();}catch(Exception e){}}//no effect, but hear for sanity's sake
}
To read the and decrypt, just read the file as bytes, decrypt the bytes, then send the byte stream to ImageIO
InputStream is = null;
ByteArrayOutputStream os = null;
ByteArrayInputStream input = null;
try{
is = new FileInputStream(inputFile);
os = new ByteArrayOutputStream ();
byte[] buffer = new byte[500];
int len = -1;
while ( ( len = is.read(buffer) ) != -1 ){
os.write(buffer, 0, len);
}
byte[] fileBytes = os.toByteArray();
decrypt(fileBytes);
input = new ByteArrayInputStream(fileBytes);
Image image = ImageIO.read(input);
}catch(IOException io){
io.printStackTrace();
}finally{
if ( is != null ){try{is.close();}catch(Exception e){}}
if ( os != null ){try{os.close();}catch(Exception e){}}
if ( input != null ){try{input.close();}catch(Exception e){}}
}
The type of encryption you use is your choice. You can use a simple Cipher to encrypt the byte array using a bitwise exclusive or (^)
for ( int i = 0; i < bytes.length; i++ ){
bytes[i] = (byte)(bytes[i] ^ 123);
}
Or more fancy encryption using a Cipher
Note that for animated gif's, you may need to search for a way to save the frames of the gif (for instance see this)

creating .bmp image file from Bitmap class

I've created an application that uses sockets in which the client receives the image and stores the data of the image in Bitmap class....
Can anyone please tell me how to create a file named myimage.png or myimage.bmp from this Bitmap object
String base64Code = dataInputStream.readUTF();
byte[] decodedString = null;
decodedString = Base64.decode(base64Code);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0,decodedString.length);
Try following code to save image as PNG format
try {
FileOutputStream out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
}
out.flush();
out.close();
Here, 100 is quality to save in Compression. You can pass anything between 0 to 100. Lower the digit, poor quality with decreased size.
Note
You need to take permission in Android Manifest file.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Edit
To save your image to .BMP format, Android Bitmap Util will help you. It has very simple implementation.
String sdcardBmpPath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/sample_text.bmp";
Bitmap testBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.sample_text);
AndroidBmpUtil bmpUtil = new AndroidBmpUtil();
boolean isSaveResult = bmpUtil.save(testBitmap, sdcardBmpPath);
try {
FileOutputStream out = new FileOutputStream(filename);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}

Categories