I have an Array of java.lang.Bytes[] in Android and I want to save it to a SQLLite table into a BLOB column.
I created the table and columns etc. I am unsure of how to save the Array as a BLOB as is.
public void AddUpdateKeys(int deviceID, String key, Boolean learned, Byte[] rawKey)
{
... // other code
ContentValues cv = new ContentValues();
cv.put(colKeyDevID, deviceID);
cv.put(colKeyLearned, key);
cv.put(colKeyLearned, learned ? 1 : 0 );
cv.put(colKeyData, rawKey); <-- Here is the issue, how to convert Type Byte[] to byte[]
How do I convert the Raw data that is in java.lang.Byte[] to byte[], I have tried
private byte[] getBytes(Byte[] learnedKey) {
byte[] result = new byte[learnedKey.length];
for(int i=0; i<learnedKey.length; i++){
result[i] = learnedKey[i].byteValue();
}
return result;
}
But is just "crashes", I also checked the the rawKey contains data? I am new to Android SQLLite Java. I want to Save the raw data of Byte[] into a Blob and read it back later and use it again.
actually An SQL BLOB type stores a large array of binary data (bytes) as the value in a column of a database.
so use column value type should specified as blob over table.and then save your byte[] into that.you should have to follow these steps over there(exm. image):
1-convert image to bitmap.
2-convert bitmap to Byte array.
public static byte[] getBytesFromBitmap(Bitmap bitmap) {
if (bitmap!=null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
return null;
}
3-make column type as blob.
4-save this byte array to that column.
Related
I've been struggling for a while now with this, and i want to be able to store an image to my database. I know storing an image to a database directly is bad practice but i simply do not know enough to be able to do it another way.
So, i'm currently stuck with a few issues.
Firstly, I'm not even sure my path is correct; i want to get a drawable file and store it to my database and there must be an easier way than doing a path straight from the C drive right?
Secondly, I don't know much about this but i need to convert my file to a bitmap so that it can be converted to a byte array? And i'm not sure how to do this exactly.
I've tried several things, wrote this code out about 10 times already in different ways and not getting anywhere. Thanks all for help in advance.
public void insertAvatar(String Email, byte[] head) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
String sql = "INSERT INTO Avatar VALUES (?, ?)";
File head = new File("C:\\Users\\PC\\Desktop\\capaa\\src\\main\\res\\drawable\\head2.png");
Bitmap imageToStoreBitmap = head; // doesn't work as my file isnt a bitmap yet
objectByteArrayOutputStream = new ByteArrayOutputStream();
imageToStoreBitmap.compress(Bitmap.CompressFormat.JPEG, 100, objectByteArrayOutputStream);
imageInBytes = objectByteArrayOutputStream.toByteArray();
contentValues.put("Email", Email);
contentValues.put("head", imageInBytes);
long checkIfQueryRuns = db.insert("Avatar", null, contentValues );
}
You need to use Blob to store images in your SQLite database.
Create a table to store the images
CREATE TABLE " + DB_TABLE_NAME + "("+
KEY_NAME + " TEXT," +
KEY_IMAGE + " BLOB);";
To store an image in the table
public void addImage( String name, byte[] image) throws SQLiteException{
ContentValues cv = new ContentValues();
cv.put(KEY_NAME, name);
cv.put(KEY_IMAGE, image);
database.insert( DB_TABLE_NAME, null, cv );
}
As you can see before inserting the image to the table, you need to convert the bitmap to a byte array.
// To convert from bitmap to byte array
public static byte[] getImageBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0, stream);
return stream.toByteArray();
}
To retrieve image from database
//search your image using the key and get the cursor
............
byte[] image = cursor.getBlob(1);
............
As you can see the image returned is in a byte array. Now you can convert this byte array to bitmap to use in your app.
//To convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
Having written the answer, I myself is not a big fan of storing images in the database. I am not sure what is your need for storing the images but you can check the following libraries to handle images in your app.
https://github.com/bumptech/glide/
https://square.github.io/picasso/
https://github.com/nostra13/Android-Universal-Image-Loader
When i make upload of a image in Android to the server (C #) it generates an error converting the image to byte Array, this happens with some images which is very strange because this error is not always generated, that is, depending the image is correctly converted or not.
The conversion code:
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapPhoto.compress(Bitmap.CompressFormat.JPEG, 50, stream);
final byte[] img_byte = stream.toByteArray();
final String imageString = Base64.encodeToString(img_byte, Base64.DEFAULT);
When receiving in C# I make the following conversion in the string, generating a byte Array and then for the MemoryStream.
byte[] novaFoto = Convert.FromBase64String(NovaFoto.FotoString);
using (MemoryStream stream = new MemoryStream(novaFoto))
{
Image image = Image.FromStream(stream);
}
depending at the image the error appears in either Convert.FromBase64String or Image.FromStream.
Can anyone help me with this? If you have another method i like this.Thanks!!
I am fetching image data from a hive which is stored as binary data like
by using an InputStream object. The problem is when I am trying to encode the image, it's getting encoded but again when I am trying to decode the same encoded image it's throwing an error.
My program looks like this:
File file=new File("path");
java.io.InputStream in = rs1.getBinaryStream("entity_image");
OutputStream f = new FileOutputStream(file);
int c=0;
while((c=in.read())>-1)
{
//System.out.println(c);
f.write(c);
}
byte[] imageBytes = new byte[(int)file.length()];
in.read(imageBytes, 0, imageBytes.length);
in.close();
String imageStr = encodeImage(imageBytes);//method that returns the encoded base64 String.
byte[] imageByteArray = decodeImage(imgstring);//method returning byte []
f.write(imageByteArray);//writing the decoded image to the file
The new image file is saying that it contains error while opening?
Are there any other ways available for fetching the image data from the hive?
I checked with getbytes() method, but it says the method is not supported.
I am writing meta data inside PNG image using below code:
public synchronized static byte[] writeMetaDataInPNGImage(BufferedImage buffImg,
String key, String value)
{
byte[][] image = null;
try
{
ImageWriter writer = ImageIO.getImageWritersByFormatName("png").next();
ImageWriteParam writeParam = writer.getDefaultWriteParam();
ImageTypeSpecifier typeSpecifier = ImageTypeSpecifier
.createFromBufferedImageType(BufferedImage.TYPE_INT_RGB);
// adding metadata
IIOMetadata metadata = writer.getDefaultImageMetadata(typeSpecifier, writeParam);
IIOMetadataNode textEntry = new IIOMetadataNode("tEXtEntry");
textEntry.setAttribute("keyword", key);
textEntry.setAttribute("value", value);
IIOMetadataNode text = new IIOMetadataNode("tEXt");
text.appendChild(textEntry);
IIOMetadataNode root = new IIOMetadataNode("javax_imageio_png_1.0");
root.appendChild(text);
int width = buffImg.getWidth();
int height = buffImg.getHeight();
metadata.mergeTree("javax_imageio_png_1.0", root);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageOutputStream stream = ImageIO.createImageOutputStream(baos);
writer.setOutput(stream);
writer.write(metadata, new IIOImage(buffImg, null, metadata), writeParam);
stream.close();
return baos.toByteArray();
// return ImageIO.read(new ByteArrayInputStream(baos.toByteArray()));
}
catch (Exception e)
{
System.out.println("Exception while writing \t " + e.getMessage() + " :: "
+ e.getStackTrace());
e.printStackTrace();
}
return null;
}
After writing meta data I am returning byte array with meta data and image data.
byte[] pngjdata = writeMetaDataInPNGImage(img.getAsBufferedImage(),"key", "hello");
If I save the image with pngjdata[] I am able to see the meta data inside image, but if I create BufferedImage from this byte array and save it I am not seeing written meta data.
InputStream in1 = new ByteArrayInputStream(pngjdata);
BufferedImage brImage = ImageIO.read(in1);
Why is brImage not having the meta data written by me?
Why is brImage not having the meta data written by me?
A BufferedImage does not contain the meta data you are looking for. The BufferedImage instance just represents pixel values, color model, sample model etc., or in other words the data necessary to display the image. There's also no API to set/get meta data (but it could be you are confused by the getProperty(name) and related methods that is inherited from the legacy AWT Image API).
Meta data in the ImageIO API is represented as instances of IIOMetadata and it's various DOM-like forms you can obtain via the getAsTree(..) method (like "javax_imageio_png_1.0" for PNG, or the "standard" "javax_imageio_1.0" format).
To keep both pixel data and meta data organized together in your application, you can use the IIOImage class.
You can read both pixel data and meta data together, using the ImageReader.readAll(index, param) method. You can write both at the same time, using ImageWriter.write(null, iioImage, param), like you already do above (just note that the first param to the write method is the stream meta data, which is different from the image meta data, for PNG just pass null).
I have tried several different methods found in the java documentation, as well as several solutions from other SO questions and have successfully gotten a Bitmap to convert to a byte[] and back again.
The problem is that I now need to convert this byte[] to a String, then back to a byte[], then back to a Bitmap again. To recap what I need:
Bitmap -> byte[] -> String -> byte[] -> Bitmap
I know this sounds strange but what I'm trying to accomplish must be done this way. Below is what I have tried, if anyone could point out what I'm doing wrong I'd greatly appreciate it!
Bitmap bitmap = mv.getDrawingCache();
// Convert bitmap to byte[]
ByteArrayOutputStream output = new ByteArrayOutputStream(bitmap.getByteCount());
bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
byte[] imageBytes = output.toByteArray();
// Convert byte[] to string
// I have also tried using Base64.encodeToString(imageBytes, 0);
String encodedString = new String(imageBytes);
// Convert string to byte[]
byte[] newImageBytes = encodedString.getBytes();
if (imageBytes == newImageBytes) {
Toast.makeText(SignatureActivity.this, "SUCCESS!!", Toast.LENGTH_SHORT).show();
} else { // Sadly, we always get to this point :(
Toast.makeText(SignatureActivity.this, "BOOO", Toast.LENGTH_SHORT).show();
}
// Convert byte[] back to bitmap
bitmap = BitmapFactory.decodeByteArray(newImageBytes, 0, newImageBytes.length);
Again, going Bitmap -> byte[] -> Bitmap was successful, but adding in the conversion to a String and back is causing the final Bitmap to write an image of 0kb.
The problem is not in the conversion, but how you verify the result. using == to compare two arrays only returns true if they are the same array reference. Since you create a new array with byte[] newImageBytes = encodedString.getBytes(); This will always be false.
See this question for reference.
On another note, if you are going to transfer or use the string in some way, it is probably better to use Base64.encodeToString(imageBytes, Base64.NO_WRAP); to get a string, and get it back with Base64.decode(encodedString, Base64.NO_WRAP).
You can also get the byte array without compressing it, with the copyPixelsToBuffer() method (see this question for an example).