I had two doubts:
1. When i am trying to print The byte array i am getting from java into client side.I am getting strange value kind. I am not sure whether it's a byte array or pixel data.If it's not byte array then what correction needed to do.Code reference are pasted below
2.currently i am reading image from the database and writing into one byte array in server side and i am adding this byte array into json object and sending.But image is not getting displayed Please see the code below:
//this line will fetch the image data from db and i am storing into byte array
byte[] imageData = smpResource.getValue();
//i am adding this byte array into json object and sending.
JSONObject result = new JSONObject();
result.put("image", imageData);
//Client side code looks like:
var temp = null;
var jqxhr = jQuery.post(
'$link.getContextPath()/setEmployee.do',
{
empID: getSelectedEmpID(), empName: getSelectedEmpName()
},
function (data) {
jQuery.each(data, function(field, value){
// here in value i will be getting that byte array and i am storing in the below img src
if( "image" == field ) {
temp = value;
// please check the attachments and please confirm whether it was printing byte array or pixel data
alert("temp" + temp);
}
});
selectedImage.innerHTML = "<img src='data:image/jpg;base64, temp'/>";
,
"json"
).error( function(){
// if there was an error, select the parent...
selectedTreeNode.remove();
});
}
Might be it got little complicated to make you understand guyz but i tried my best.But let me know i will try in some other way.
To show in image with a data/base64 url, you need to encode it in Base64 format (see http://en.wikipedia.org/wiki/Base64). You could modify your backend to write your image into base64 format (see Java BufferedImage to PNG format Base64 String), as a string rather than an array. It's also way more compact for your JSON!
Related
I want to store some image descriptors on a server so that when image matching on an android phone I can fetch the precomputed image descriptors rather then doing it on the fly. I have successfully created an application that can take an input image and output the best match but I am having some trouble with placing the image descriptor matrix into a JSON file.
Below I have placed some code that I have tried to adapt to perform the function I want but I run into an error with these lines:
mat.get(0, 0, data);
The error it gives is:
Mat data type is not compatible: 5
The descriptor matrix is of type CV_32FC1 but it treats it as CV_8SC1. Full code is underneath, the idea is that I will pass in descriptor matrix to matToJson and then store the output on the server and then use matFromJson to retrieve the contents of the JSON file. I also cannot resolve Base64.DEFAULT as it shows an error. Any help would be greatly appreciated.
public static String matToJson(Mat mat){
JsonObject obj = new JsonObject();
if(mat.isContinuous()){
int cols = mat.cols();
int rows = mat.rows();
int elemSize = (int) mat.elemSize();
byte[] data = new byte[cols * rows * elemSize];
mat.get(0, 0, data);
obj.addProperty("rows", mat.rows());
obj.addProperty("cols", mat.cols());
obj.addProperty("type", mat.type());
// We cannot set binary data to a json object, so:
// Encoding data byte array to Base64.
String dataString = new String(Base64.encode(data, Base64.DEFAULT)); //Error here as well .default does not exist
obj.addProperty("data", dataString);
Gson gson = new Gson();
String json = gson.toJson(obj);
return json;
} else {
System.out.println("Mat not continuous.");
}
return "{}";
}
public static Mat matFromJson(String json){
JsonParser parser = new JsonParser();
JsonObject JsonObject = parser.parse(json).getAsJsonObject();
int rows = JsonObject.get("rows").getAsInt();
int cols = JsonObject.get("cols").getAsInt();
int type = JsonObject.get("type").getAsInt();
String dataString = JsonObject.get("data").getAsString();
byte[] data = Base64.decode(dataString.getBytes(), Base64.DEFAULT);
Mat mat = new Mat(rows, cols, type);
mat.put(0, 0, data);
return mat;
}
Found a solution to the issue here, the problem was being caused by using the incorrect data type in the array. rather than using byte it should have been float. however the solution I have linked above is much better in that it checks the data type prior to encoding the data.
I have images in my local database which I want to populate in a listview.
This is what I'm doing :
...
bitmap[i] = MySQLiteHelper.getImage(images[i]);
// This fetches the bitmap image from database
...
Here, I'm converting my Bitmap to a Drawable.
d[i] = new BitmapDrawable(getResources(),bitmap[i]);
Then I'm using this Drawable in HashMap's put method to set it as a listView item.
hm.put("img", String.valueOf(d[i]));
// put() accepts java.lang.String as input.
But the image is not displayed in the listview. I'm able to display all the text, but not the image.
I'm getting the following error in my LogCat :
BitmapFactory﹕ Unable to decode stream: java.io.FileNotFoundException: android.graphics.drawable.BitmapDrawable#3ab28e36: open failed: ENOENT (No such file or directory)
resolveUri failed on bad bitmap uri: android.graphics.drawable.BitmapDrawable#3ab28e36
What am I doing wrong here? I think that when converting that Bitmap to Drawable, the drawable is holding a temporary value and the put() cannot access that? What is wrong here folks, any help please?
EDIT :
My HashMap code :
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<len;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("img", String.valueOf(d[i]));
hm.put("tit", " Title : " + title[i]);
hm.put("init", " Initial Price : " + init_price[i]);
hm.put("cur"," Current Price : " + cur_price[i]);
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "img","tit","init","cur" };
// Ids of views in listview_layout
int[] to = { R.id.img,R.id.tit,R.id.init,R.id.cur};
getImage() method :
The image (Bitmap) is stored in the database as BLOB. I obtained it as a ByteArray.
Now, I'm converting it back to Bitmap using the below method.
// convert from byte array to bitmap
public static Bitmap getImage(byte[] image) {
return BitmapFactory.decodeByteArray(image, 0, image.length);
}
My Logcat : after using Base64 to convert Bitmap to String
(Note: consider using the new RecyclerView instead of a ListView for better performance)
What you are trying to do is either converting a String to a BitmapDrawable (in case MySQLiteHelper.getImage() returns a String as a path pointing to an image, since usually you won't store binary data in a database) OR converting a BitmapDrawable to a String. Both cases actually make no sense.
The way it is usually done: implementing a helper class and then parameterizing your ListView's Adapter with its instances. There are literally tons of examples around the web, look at this one, or that one which uses a database
From the error message it seems the problem is elsewhere in the code.
BitmapFactory﹕ Unable to decode stream: java.io.FileNotFoundException
This probably means you are decoding the file with a location and the location is invalid. Perhaps you are using BitmapFactory.decodeFile?
Check in your code if you are using BitmapFactory and make sure you are passing the correct location if available.
In my application, I want to change the raw byte data to the audio. So, at first I receive the data and add it to a byte array list and than I want to change the whole array list to the audio. As the data is raw through audio jack, I would appreciate if you let me know which audio format is suitable (wav,3gp and so on)? Also, I have a problem with saving this data in a file. This is my code. in line of fileOuputStream.write( audiod.toArray()), it give an error and asked me to change the type of audiod to byte.
private static ArrayList<Byte> audiod = new ArrayList<Byte>();
audioFilePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/myaudio.wav";
if (dg == 1) {
//audiod.append(data[i]);
for (int i = 0; data != null && i < data.length; i++) {
audiod.add(data[i]);
}
if (stt.equalsIgnoreCase(("r"))) {
dg = 0;
recordButton.setEnabled(true);
File file = new File(audioFilePath);
try {
FileOutputStream fileOuputStream = new FileOutputStream(audioFilePath);
fileOuputStream.write( audiod.toArray());
fileOuputStream.close();
System.out.println("Done");
}
catch(Exception e) {
e.printStackTrace();
}
}
}
audiod.toArray() will give you a Byte[], however you need a byte[]. In Java there are so called wrapper classes for the primitive data types. A Byte is an object that holds byte values.
Why do you use a list of Byte at all? It needs a lot more memory than a simple byte[] you seem to have anyhow (data).
The data format (wav,3gp and so on) depends on how you got your data.
I have a 'small' problem. In a database documents contain a richtextfield. The richtextfield contains a profile picture of a certain contact. The problem is that this content is not saved as mime and therefore I can not calculate the url of the image.
I'm using a pojo to retrieve data from the person profile and use this in my xpage control to display its contents. I need to build a convert agent which takes the content of the richtextitem and converts it to mime to be able to calculate the url something like
http://host/database.nsf/($users)/D40FE4181F2B86CCC12579AB0047BD22/Photo/M2?OpenElement
Could someone help me with converting the contents of the richtextitem to mime? When I check for embedded objects in the rt field there are none. When I get the content of the field as stream and save it to a new richtext field using the following code. But the new field is not created somehow.
System.out.println("check if document contains a field with name "+fieldName);
if(!doc.hasItem(fieldName)){
throw new PictureConvertException("Could not locate richtextitem with name"+fieldName);
}
RichTextItem pictureField = (RichTextItem) doc.getFirstItem(fieldName);
System.out.println("Its a richtextfield..");
System.out.println("Copy field to backup field");
if(doc.hasItem("old_"+fieldName)){
doc.removeItem("old_"+fieldName);
}
pictureField.copyItemToDocument(doc, "old_"+fieldName);
// Vector embeddedPictures = pictureField.getEmbeddedObjects();
// System.out.println(doc.hasEmbedded());
// System.out.println("Retrieved embedded objects");
// if(embeddedPictures.isEmpty()){
// throw new PictureConvertException("No embedded objects could be found.");
// }
//
// EmbeddedObject photo = (EmbeddedObject) embeddedPictures.get(0);
System.out.println("Create inputstream");
//s.setConvertMime(false);
InputStream iStream = pictureField.getInputStream();
System.out.println("Create notesstream");
Stream nStream = s.createStream();
nStream.setContents(iStream);
System.out.println("Create mime entity");
MIMEEntity mEntity = doc.createMIMEEntity("PictureTest");
MIMEHeader cdheader = mEntity.createHeader("Content-Disposition");
System.out.println("Set header withfilename picture.gif");
cdheader.setHeaderVal("attachment;filename=picture.gif");
System.out.println("Setcontent type header");
MIMEHeader cidheader = mEntity.createHeader("Content-ID");
cidheader.setHeaderVal("picture.gif");
System.out.println("Set content from stream");
mEntity.setContentFromBytes(nStream, "application/gif", mEntity.ENC_IDENTITY_BINARY);
System.out.println("Save document..");
doc.save();
//s.setConvertMime(true);
System.out.println("Done");
// Clean up if we are done..
//doc.removeItem(fieldName);
Its been a little while now and I didn't go down the route of converting existing data to mime. I could not get it to work and after some more research it seemed to be unnecessary. Because the issue is about displaying images bound to a richtextbox I did some research on how to compute the url for an image and I came up with the following lines of code:
function getImageURL(doc:NotesDocument, strRTItem,strFileType){
if(doc!=null && !"".equals(strRTItem)){
var rtItem = doc.getFirstItem(strRTItem);
if(rtItem!=null){
var personelDB = doc.getParentDatabase();
var dbURL = getDBUrl(personelDB);
var imageURL:java.lang.StringBuffer = new java.lang.StringBuffer(dbURL);
if("file".equals(strFileType)){
var embeddedObjects:java.util.Vector = rtItem.getEmbeddedObjects();
if(!embeddedObjects.isEmpty()){
var file:NotesEmbeddedObject = embeddedObjects.get(0);
imageURL.append("(lookupView)\\");
imageURL.append(doc.getUniversalID());
imageURL.append("\\$File\\");
imageURL.append(file.getName());
imageURL.append("?Open");
}
}else{
imageURL.append(doc.getUniversalID());
imageURL.append("/"+strRTItem+"/");
if(rtItem instanceof lotus.domino.local.RichTextItem){
imageURL.append("0.C4?OpenElement");
}else{
imageURL.append("M2?OpenElement");
}
}
return imageURL.toString()
}
}
}
It will check if a given RT field is present. If this is the case it assumes a few things:
If there are files in the rtfield the first file is the picture to display
else it will create a specified url if the item is of type Rt otherwhise it will assume it is a mime entity and will generate another url.
Not sure if this is an answer but I can't seem to add comments yet. Have you verified that there is something in your stream?
if (stream.getBytes() != 0) {
The issue cannot be resolved "ideally" in Java.
1) if you convert to MIME, you screw up the original Notes rich text. MIME allows only for sad approximation of original content; this might or might not matter.
If it matters, it's possible to convert a copy of the original field to MIME used only for display purposes, or scrape it out using DXL and storing separately - however this approach again means an issue of synchronization every time somebody changes the image in the original RT item.
2) computing URL as per OP code in the accepted self-answer is not possible in general as the constant 0.C4 in this example relates to the offset of the image in binary data of the RT item. Meaning any other design of rich text field, manually entered images, created by different version of Notes - all influence the offset.
3) the url can be computed correctly only by using C API that allows to investigate binary data in rich text item. This cannot be done from Java. IMO (without building JNI bridges etc)
I am a .NET Developer, but the question I am having is not related to .NET
Please keep this in mind even if my question sounds very trivial.
This is my question:
We have an swf in the browser, which communicates with a java extension
Its done using Smartfox Server(Used for MMO apllications)
From the swf we are grabbing a portion of the screen as "Byte Array" in action script(3).
And in Java, we are calling a function that converts the ByteArray to Image and then saves it.
Our Java developer is encountering the error
java.lang.illegalArgumentException
when the java function executes.
So basically, what I would like to know is this:
How to accept the object type Byte Array from ActionScript in Java?
Whats Java object type that is mapped to Byte Array in ActionScript?
The conversion part is easy, I dare say.
Update:
The code in the ActionScript Section
public function savePhoto(uName:String, ba:ByteArray, descr:String):void{
var obj:Object = {};
obj.arr = ba;
obj.desc = descr;
sfsConnectobj.photoSectionSave(obj,"save");
}
public function photoSectionSave(targetObject:Object,type:String) {
sfs.sendXtMessage("trialjava", "save", targetObject);
}
The first function calls the SmartFox Extension in Java.
The extension name is "trialjava.js"
The Java Code that accepts the function is
public void handleRequest(String cmd, ActionscriptObject ao, User u, int fromRoom)
{
try {
ActionscriptObject arr = ao.getObj("arr");
String dirName="C:\\";
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos;
oos = new ObjectOutputStream(bos);
oos.writeObject(ao.getObj("arr"));
oos.flush();
oos.close();
bos.close();
byte [] data = bos.toByteArray();
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(data));
ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
}
catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Array reading not succesful. Error is: "+e);
}
}
Seems like there was a small mismatch in retrieving the objects by java.
Now the error is different.
Array reading not succesful. Error is:
java.io.NotSerializableException:
it.goto
andplay.smartfoxserver.lib.ActionscriptObject
Regards,
naveenj
flash.utils.ByteArray is mapped to Java's byte[] type.
I am not sure if this is an issue, but according to Flash security model, if SWF is loading media from any host/domain other that the one it was loaded, screen capture would result in error.
Can you check the byte array you received? What is its size? And try to print its starting few values.
Byte array is not received directly. It comes inside an AS object. The real question here is how to get this byte array inside the ActionScript object to a Java byte array object.
I am the aforesaid Java developer and I am doing this.