I'm trying to figure out how to add the following data to my json object. Could someone show me how to do this.
{
"main_img":"Base64 String"
}
However, the following is the result of using this code, to come out.
final int COMPRESSION_QUALITY = 100;
String encodedImage;
ByteArrayOutputStream byteArrayBitmapStream = new ByteArrayOutputStream();
bitmapPicture.compress(Bitmap.CompressFormat.JPEG, COMPRESSION_QUALITY,
byteArrayBitmapStream);
byte[] b = byteArrayBitmapStream.toByteArray();
encodedImage = "data:image/JPEG;base64," + Base64.encodeToString(b, Base64.DEFAULT);
JSONObject jObject = new JSONObject();
jObject.put("main_img", result);
{
"main_img":"Base64 String
It is displayed with }, " is missing.
Related
How do I load an image from my database to my android application and put it in a listview. The database is MySQL and the image is stored in png format
Here is my codes for retrieving data in my database. The a_emblem is the imageview and the image in my json file
private void showResult() {
JSONObject jsonObject;
ArrayList<HashMap<String, String>> list = new ArrayList<>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY1);
for (int i = 0; i < result.length(); i++) {
JSONObject jo = result.getJSONObject(i);
String a_shortcut = jo.getString(Config.TAG_a_shortcut);
String a_emblem = jo.getString(Config.TAG_a_emblem);
String gold = jo.getString(Config.TAG_gold);
String silver = jo.getString(Config.TAG_silver);
String bronze = jo.getString(Config.TAG_bronze);
String total = jo.getString(Config.TAG_total);
HashMap<String, String> match = new HashMap<>();
match.put(Config.TAG_a_shortcut, a_shortcut);
match.put(Config.TAG_a_emblem, a_emblem);
match.put(Config.TAG_gold, gold);
match.put(Config.TAG_silver, silver);
match.put(Config.TAG_bronze, bronze);
match.put(Config.TAG_total, total);
list.add(match);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
getActivity(), list, R.layout.standlayout,
new String[]{Config.TAG_a_shortcut, Config.TAG_a_emblem, Config.TAG_gold, Config.TAG_silver, Config.TAG_bronze, Config.TAG_total},
new int[]{R.id.shortcut, R.id.img, R.id.gold, R.id.silver, R.id.bronze, R.id.total});
lv.setAdapter(adapter);
}
use Picasso or glide here is the url for you
Picasso
or
Glide
Here is what you can do.
Convert your image to a bitmap.
Convert your image to a base64 string and save this base64 string in the database.
Convert the base64 string back to the image while using it in the adapter.
Set bitmap in ImageView.
It should definitely work. Code for reference
Convert drawable to Bitmap
Bitmap icon = BitmapFactory.decodeResource(context.getResources(),
R.drawable.icon_resource);
Use the following method to convert a bitmap to a byte array:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
to encode a base64 string from a byte array:
String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);
save encoded in the database.
Convert the base64 string back to Bitmap:
byte[] decodedString = Base64.decode(encoded , Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Set the bitmap to the image view:
imageView.setImageBitmap(bitmap);
I creating an application in which I am using mandrill app API to send emails. Emails without attachment are delivering, but when I attach image to it, it is received as damaged image at receiver side. Here it is required to convert file into base64 string to pass in json array. I used this code:
public static String encodeImagetoBase64(Bitmap img) {
Bitmap image = img;
ByteArrayOutputStream byteOStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.JPEG, 100, byteOStream);
byte[] b = byteOStream.toByteArray();
String imageEncoded = Base64.encodeToString(b, Base64.DEFAULT);
Log.e("Look", imageEncoded);
return imageEncoded;
}
So can anyone tell me the solution, why image is getting damaged.
Similarly I also want to convert files with extension ".txt,.doc,.docx,.pptx,.pdf,.xls" etc as attachment, so please suggest me any source for that. Thanx
I am using this method and it is working:
public static String getFileBinary(String uploadFilePath) {
String encodedString = "0";
if (uploadFilePath.length() < 2)
return encodedString;
try {
InputStream inputStream = new FileInputStream(uploadFilePath);//You can get an inputStream using any IO API
byte[] bytes;
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
bytes = output.toByteArray();
encodedString = Base64.encodeToString(bytes, Base64.DEFAULT);
} catch (IOException es) {
}
return encodedString;
}
I tried to encrypt plaintext using the below code. The code seems encrypt the text but it doesnt decrypt to plaintext back. What am I doing wrong ?
The code:
Entity entity = new Entity("password");
byte[] ciphertext = crypto.encrypt(("data to encrypt").getBytes(),entity);
plaintext = crypto.decrypt(ciphertext,entity)
Output:
Ecrypted text:[B#417a110
Decrypted text:[B#417df20
The following code can encrypt/decrypt string
KeyChain keyChain = new SharedPrefsBackedKeyChain(context, CryptoConfig.KEY_256);
crypto = AndroidConceal.get().createDefaultCrypto(keyChain);
public static String encrypt(String key, String value) throws KeyChainException, CryptoInitializationException, IOException {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
OutputStream cryptoStream = crypto.getCipherOutputStream(bout, Entity.create(key));
cryptoStream.write(value.getBytes("UTF-8"));
cryptoStream.close();
String result = Base64.encodeToString(bout.toByteArray(), Base64.DEFAULT);
bout.close();
return result;
}
public static String decrypt(String key, String value) throws KeyChainException, CryptoInitializationException, IOException {
ByteArrayInputStream bin = new ByteArrayInputStream(Base64.decode(value, Base64.DEFAULT));
InputStream cryptoStream = crypto.getCipherInputStream(bin, Entity.create(key));
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int read = 0;
byte[] buffer = new byte[1024];
while ((read = cryptoStream.read(buffer)) != -1) {
bout.write(buffer, 0, read);
}
cryptoStream.close();
String result = new String(bout.toByteArray(), "UTF-8");
bin.close();
bout.close();
return result;
}
I have found the answer.
The reason is we were printing the byte array instead of the String.
The array is going to comprise of a set of bytes so that's what we saw when we printed them out in the logcat.
To see the actual String, we just need to put the byte[] into a new String(byte[]) - this is taken from the official facebook examples with my modifications:
Crypto crypto = new Crypto(
new SharedPrefsBackedKeyChain(getActivity()),
new SystemNativeCryptoLibrary());
if (!crypto.isAvailable()) {
Log.e("Crypto","Crypto is missing");
}
String password = "Password";
Entity entity = new Entity("TEST");
byte[] encryptedPass = new byte[0];
byte[] b = password.getBytes(Charset.forName("UTF-8"));
try {
encryptedPass = crypto.encrypt(b, entity);
Log.e("Crypto Encrypted", new String(encryptedPass));
byte[] decryptedPass = crypto.decrypt(encryptedPass, entity);
Log.e("Crypto Decrypted ", new String(decryptedPass));
} catch (KeyChainException e) {
e.printStackTrace();
} catch (CryptoInitializationException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Results:
08-02 19:31:11.237 29364-29364/? E/Crypto Encrypted﹕
0��&�?B�6���H���`��"�1��xx� 08-02 19:31:11.237 29364-29364/?
E/Crypto Decrypted﹕ Password
Base64.encodeToString(cipherText, Base64.DEFAULT); then store it.
It might be a little too late but I had the same issue and managed to get the plain text after the decryption.
What you really need to do is to use ByteArrayOutputStream like the following code:
Entity entity = new Entity("password");
byte[] ciphertext = crypto.encrypt(("data to encrypt").getBytes(),entity);
byte[] plainText = crypto.decrypt(ciphertext,entity);
ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(plainText, 0, plainText.length);
String decryptedPassword = out.toString();
out.close();
Hope this helps.
i have a problem, i am uploading image on server but it is not. i have convert image in base64 and get through json. but json is not properly closed due to this i m getting error. error id om postimafe variable. in this variable {"key"""encode, here is json is not closed.
// code for convert base64
public static String getBase64String(String baseFileUri)
{
String encodedImageData = "";
try
{
System.out.println("getBase64String method is called :" +baseFileUri);
Bitmap bm = BitmapFactory.decodeFile(baseFileUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bm is the bitmap object
byte[] b = baos.toByteArray();
encodedImageData = Base64.encodeToString(b, Base64.DEFAULT);
//ArrayList<NameValuePair> imagearraylistvalue = new ArrayList<NameValuePair>();
//imagearraylistvalue.add(new BasicNameValuePair("image", encodedImage));
System.out.println("encode data in upload file :" +encodedImageData );
}
catch(Exception ex)
{
System.out.println("Exception in getBase64String method in Utility class :" +ex);
}
return encodedImageData ;
}
// code for json and uplod base64 to server but i m getting error
System.out.println("fullupload image for 1:" +fulluploadimgpath);
String base64String = Utility.getBase64String(fulluploadimgpath);
System.out.println("base64String is in :" +base64String);
if (base64String != null)
{
JSONObject postImageData = new JSONObject();
postImageData.put("media",base64String);
System.out.println("post image :" +postImageData);
HttpResponse imgPostResponse = Utility.postDataOnUrl(Utility.getBaseUrl()+"user/upload",obj.toString());
System.out.println("fullupload image for imgPostResponse:" +imgPostResponse);
if (imgPostResponse != null)
{
String imgResponse = Utility.readUrlResponseAsString(imgPostResponse);
System.out.println("imgResponse is in imgResponse :" +imgResponse);
if (imgResponse != null|| imgResponse.trim().length() != 0)
{
JSONObject jResObj = new JSONObject();
if (jResObj.getBoolean("rc"))
{
obj.put(hidobj.getReceiveAs(),jResObj.getLong("ident"));
}
}
String encodedImageData =getEncoded64ImageStringFromBitmap(your bitmap);
public String getEncoded64ImageStringFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
byte[] byteFormat = stream.toByteArray();
// get the base 64 string
String imgString = Base64.encodeToString(byteFormat, Base64.NO_WRAP);
return imgString;
}
This is my first question on stackoverflow.
My problem is: i'm trying to convert byte[] into image. The byte[] comes from JSON and it's in this format:
"4oCwUE5HDQoaCgAAAA1JSERSAAAAfwAAAFAIBgAAADBHwqrDsAAAAAlwSFlzAAAAJwAAACcBKgnigJhPAAAgAElEQVR4xZPCrMK9ecWSZcOZfcOfw7c5w5vCvW/CqXp..." it goes for another 100 lines.
The code where the problem occurs:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(PlayersListActivity.URL);
httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(httpEntity);
// if this is null the web service returned an empty page
if(httpEntity == null) // response is empty so exit out
return null;
String jsonString = EntityUtils.toString(bufferedEntity);
// again some simple validation around the returned string
if(jsonString != null && jsonString.length() != 0) // checking string returned from service to grab id
{
JSONArray jsonArray = new JSONArray(jsonString);
for(int i=0; i< jsonArray.length(); i++)
{
HashMap<String, Object> map = new HashMap<String, Object>();
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
byte[] images = jsonObject.getString("image").getBytes();
Bitmap btm = BitmapFactory.decodeByteArray(images, 0, images.length);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
btm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bitmap btm2 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageBitmap(btm2);
map.put("name", name.toString());
map.put("image", images.toString());
Log.d("JSON OBJECTS:", jsonObject.toString());
Log.d("WHATS IN MAP:", map.toString());
playersList.add(map);
And ofcourse error that I'm getting in LogCat:
SkImageDecoder:: Factory returned null.
java.lang.NullPointerException
and it points out on this line:
Bitmap btm2 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
I have done reseach but nothing really points on what I'm missing.
Any ideas??
Thanks!!
4oCwUE5HDQoaCgAAAA1JSERSAAAAfwAAAFAIBgAAADBHwqrDsAAAAAlwSFlzAAAAJwAAACcBKgnigJhPAAAgAElEQVR4xZ
PCrMK9ecWSZcOZfcOfw7c5w5vCvW/CqXp..." it goes for another 100 lines.
Its seems like its not a byte[] but its a Base64 String
So try like
String base64 = jsonObject.getString("image");
byte[] decodedString = Base64.decode(base64, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
image.setImageBitmap(decodedByte);
Hope this help you.
**Your web service is the UTF-8 decoder**
String str=[Base64];
str = URLDecoder.decode(str, "UTF-8");
ImageView imgView.setImageBitmap(StringToBitMap(str));
public static Bitmap StringToBitMap(String image) {
try {
byte[] encodeByte = Base64.decode(image.getBytes(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
encodeByte.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}
}