How to convert Uri image into Base64? - java

I have write code to convert image from file location into base64. I can easily convert image into base64 from absolute file location like: C:/Users/Java Engineer/Desktop/test/gallery/magar/Kanuglam.jpg , but I can not convert from location like
. I want to convert image to use in android from web-service.
Here is code sample :
/**
* TEST JSON
*/
String convertToJsonArrayWithImageForMovieDetailTest(ResultSet rs) {
System.out.println("I am insied json converter");
JSONArray list = new JSONArray();
JSONObject obj ;
//File file;
File locatedFile;
FileInputStream fileInputStream;
try {
while (rs.next()) {
obj = new JSONObject();
System.out.println("inside RS");
System.out.println("date is there ha ha ");
obj.put("movie_name", rs.getString("name"));
obj.put("movie_gener", rs.getString("type"));
String is_free_stuff = rs.getString("is_free_stuff");
if (is_free_stuff == "no") {
is_free_stuff = "PAID";
} else {
is_free_stuff = "FREE";
}
obj.put("movie_type", is_free_stuff);
//String movie_image = rs.getString("preview_image");
//this does not work
String movie_image = "http://www.hamropan.com/stores/slider/2016-09-10-852311027.jpg";
//this works for me
// file = new File("C:/Users/Java Engineer/Desktop/Nike Zoom Basketball.jpg");
locatedFile = new File(movie_image);
// Reading a Image file from file system
fileInputStream = new FileInputStream(locatedFile);
if (locatedFile == null) {
obj.put("movie_image", "NULL");
} else {
byte[] iarray = new byte[(int) locatedFile.length()];
fileInputStream.read(iarray);
byte[] img64 = com.sun.jersey.core.util.Base64
.encode(iarray);
String imageString = new String(img64);
obj.put("movie_image", imageString);
}
list.add(obj);
}
} catch (Exception e) {
e.printStackTrace();
}
return list.toString();
}
this block of code works for me but it seem slow
public String imageConvertMethod(String url) throws Exception{
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (InputStream input = new URL(url).openStream()) {
byte[] buffer = new byte[512];
for (int length = 0; (length = input.read(buffer)) > 0;) {
output.write(buffer, 0, length);
}
}
byte [] byte_array = output.toByteArray();
byte[] img64 = com.sun.jersey.core.util.Base64
.encode(byte_array);
String imageString = new String(img64);
return imageString;
}

Ok, try this
bitmap = getBitmapFromUrl(image_url);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] array = stream.getByteArray();
encoded_string = Base64.encodeToString(array, 0);
Method wo load image from url
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

#thanks to Fabio Venturi Pastor
Try this:
ImageUri to Bitmap:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
final Uri imageUri = data.getData();
final InputStream imageStream = getContentResolver().openInputStream(imageUri);
final Bitmap selectedImage = BitmapFactory.decodeStream(imageStream);
String encodedImage = encodeImage(selectedImage);
}
}
Encode Bitmap in base64
private String encodeImage(Bitmap bm)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
return encImage;
}
Encode from FilePath to base64
private String encodeImage(String path)
{
File imagefile = new File(path);
FileInputStream fis = null;
try{
fis = new FileInputStream(imagefile);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG,100,baos);
byte[] b = baos.toByteArray();
String encImage = Base64.encodeToString(b, Base64.DEFAULT);
//Base64.de
return encImage;
}
output:
reference :
Take picture and convert to Base64

Related

Save drawable into parse

I saved into my project a drawable R.drawable.descarga what I need to do I that when there is no file to upload to parse it uploads this one.
This is my code.
if (requestCode == REQUEST_GALLERY_PHOTO7 && resultCode == RESULT_OK) {
Uri imageUri = data.getData();
InputStream inputStream;
try {
inputStream = getActivity().getApplicationContext().getContentResolver().openInputStream(imageUri);
Bitmap image = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
ParseFile fileInmoFotoPrinci = new ParseFile("image.jpg", byteArray);
inmoFoto8.setImageBitmap(image);
if(fileInmoFotoPrinci!=null) {
grabarImagenPrinc.put("imagen7", fileInmoFotoPrinci);
}else{
Drawable myDrawable = getResources().getDrawable(R.drawable.descarga);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
// FileOutputStream fos = new FileOutputStream(myDrawable);
//
// File file=myLogo.compress(Bitmap.CompressFormat.PNG, 100, fos);
grabarImagenPrinc.put("imagen7", myDrawable);
}
grabarImagenPrinc.saveInBackground();
} catch (FileNotFoundException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "No fue posible abrir la imagen", Toast.LENGTH_LONG).show();
}
}
i would be having the trouble in this part ...
Drawable myDrawable = getResources().getDrawable(R.drawable.descarga);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
// FileOutputStream fos = new FileOutputStream(myDrawable);
//
// File file=myLogo.compress(Bitmap.CompressFormat.PNG, 100, fos);
grabarImagenPrinc.put("imagen7", myDrawable);
i have tried to apply many StackOverflow post in this part but nothing seems to work.
The Documentation says this but I don't really understand it...
byte[] data = "Working at Parse is great!".getBytes();
ParseFile file = new ParseFile("resume.txt", data);
Also tried this code in the else statement.
Drawable d = null; // the drawable (Captain Obvious, to the rescue!!!)
Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] bitmapdata = stream.toByteArray();
ParseFile file = new ParseFile("image.jpeg", bitmapdata);
grabarImagenPrinc.put("imagen7",file);
My problem is that the drawable isnt saving to parse how it should do.
This is the code update!.
private void queryEmpresa() {
/**Ojo no es que no este sirviendo el metodo sino que el tipo de empresa asignado al usuario
* no concuerda para que llene el recycler*/
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("objectId", ParseUser.getCurrentUser().getObjectId());
query.include("Empresa");
query.getInBackground(ParseUser.getCurrentUser().getObjectId(), new GetCallback<ParseUser>() {
public void done(ParseUser object, ParseException e) {
if (e == null) {
// object will be your user and you should be able to retrieve Empresa like this
empresa = object.getParseObject("Empresa");
if (empresa != null) {
ParseObject grabarImagenPrinc = new ParseObject("PropiedadesInmobiliarias");
stringEmpresa = empresa.getObjectId();
ParseObject entity = new ParseObject("PropiedadesInmobiliarias");
Bitmap bm = ((BitmapDrawable) inmoFotoPrincipal.getDrawable()).getBitmap();
if(bm.equals("")) {
ByteArrayOutputStream myLogoStream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, myLogoStream);
byte[] myLogoByteArray = myLogoStream.toByteArray();
bm.recycle();
ParseFile myLogoFile = new ParseFile("mylogo.png", myLogoByteArray);
grabarImagenPrinc.put("imagen7", myLogoFile);
grabarImagenPrinc.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
}
});
}
entity.put("numeroBanos", edittextNumeroDeBanos.getText().toString().trim());
entity.put("descripcionAdicionalPropiedad", edittextDescripcion.getText().toString().trim());
entity.put("Empresa", ParseObject.createWithoutData("Empresa", stringEmpresa));
entity.put("NombrePropiedad", edittextNombrePropiedad.getText().toString().trim());
entity.put("Precio", edittextPrecio.getText().toString().trim());
String xx=edittextNumeroHabitaciones.getText().toString().trim();
entity.put("numeroDeHabitaciones", edittextNumeroHabitaciones.getText().toString().trim());
String xy=edittextMetrosCuadrados.getText().toString().trim();
entity.put("metrosCuadrados", edittextMetrosCuadrados.getText().toString().trim());
entity.put("valorAdministracion", edittextValorAdmin.getText().toString().trim());
entity.put("Parqueaderos", edittextParqueaderos.getText().toString().trim());
entity.saveInBackground(new SaveCallback() {
#Override
public void done(ParseException e) {
Log.i("XX","este es el error de porque no salva",e);
Intent intent = new Intent(getActivity(), MainActivity.class);
getActivity().startActivity(intent);
}
});
} else {
// something went wrong. It would be good to log.
}
}
}
});
}
This is used in a button to save with an on click listener...
look at this i made a different approach taking your suggestions davi.
try:
...
Drawable myDrawable = getResources().getDrawable(R.drawable.descarga);
Bitmap myLogo = ((BitmapDrawable) myDrawable).getBitmap();
ByteArrayOutputStream myLogoStream = new ByteArrayOutputStream();
myLogo.compress(Bitmap.CompressFormat.PNG, 100, myLogoStream);
byte[] myLogoByteArray = myLogoStream.toByteArray();
myLogo.recycle();
ParseFile myLogoFile = new ParseFile("mylogo.png", myLogoByteArray);
grabarImagenPrinc.put("imagen7", myLogoFile);
...

How to use readFileToByteArray with image from gallery

I'm trying to implement in my app the haystack.ai API. I read the documentation. I need help to change something in my code.
In the example code in the documentation, you provide the path of your image. I need to let the user choose a picture from the gallery(I know how to do that) and then convert the picture into an array of byte.
That's what I tried:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rate);
backBtn = findViewById(R.id.back_btn);
image = findViewById(R.id.imageRated);
if (getIntent().getExtras() != null) {
imageUri = Uri.parse(getIntent().getStringExtra("uri"));
image.setImageURI(imageUri);
}
backBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RateActivity.this, MainActivity.class);
startActivity(intent);
}
});
try {
getScore();
} catch (IOException e) {
e.printStackTrace();
}
}
public void getScore() throws IOException {
URL url = new URL("https://api.haystack.ai/api/image/analyze?output=json&apikey=myapikey");
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
byte[] imageData = FileUtils.readFileToByteArray(new File(imageUri.toString()));
OutputStream os = new BufferedOutputStream(conn.getOutputStream());
os.write(imageData);
os.close();
InputStream is = conn.getInputStream();
byte[] buffer = new byte[1024];
ByteArrayOutputStream responseBuffer = new ByteArrayOutputStream();
while (true) {
int n = is.read(buffer, 0, buffer.length);
if (n <= 0) {
break;
}
responseBuffer.write(buffer, 0, n);
}
String response = responseBuffer.toString("UTF-8");
Log.v("Score", response);
}
}
The logcat says :
RateActivity.getScore(Unknown Source:12) at line 62 --->
byte[] imageData = FileUtils.readFileToByteArray(new File(imageUri.toString()));
I also tried:
byte[] imageData = FileUtils.readFileToByteArray(new File(imageUri.getPath()));
The original code in the documentation is:
byte[] imageData = Files.readAllBytes(Paths.get("testImage4.jpg"));
I need to convert the selected picture for the imageData array.
How can I do that?
From your question it seems that you want to convert image URI to
byteArray.
If it is the case you can try the code below.
public void convertUriToByteArray(String uri)
{
ByteArrayOutputStream bArray = new ByteArrayOutputStream();
FileInputStream fIn = null;
try {
fIn = new FileInputStream(new File(uri));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
byte[] buf = new byte[1024];
int n;
try {
while (-1 != (n = fIn.read(buf)))
bArray.write(buf, 0, n);
} catch (IOException e) {
e.printStackTrace();
}
byte[] bytes = bArray.toByteArray();
}

Bitmap - Base64 String - Bitmap conversion android

I am encoding an image in the following way and store it in my database:
public String getStringImage(Bitmap bmp){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Now I am trying to decode it in the following way and display it in an ImageView :
try{
InputStream stream = new ByteArrayInputStream(image.getBytes());
Bitmap bitmap = BitmapFactory.decodeStream(stream);
return bitmap;
}
catch (Exception e) {
return null;
}
}
However the ImageView remains blank and the image is not displayed. Am I missing something?
Try decoding the string first from Base64.
public static Bitmap decodeBase64(String input) {
byte[] decodedByte = Base64.decode(input, 0);
return BitmapFactory.decodeByteArray(decodedByte, 0, decodedByte.length);
}
In you case:
try{
byte[] decodedByte = Base64.decode(input, 0);
InputStream stream = new ByteArrayInputStream(decodedByte);
Bitmap bitmap = BitmapFactory.decodeStream(stream);
return bitmap;
}
catch (Exception e) {
return null;
}

Storing Image on Android SDCard & Path URL in SharedPreferences

I'm currently storing the photos like so in the SharedPreferences after it's captured using ACTION_IMAGE_CAPTURE intent:
if (requestCode == REQUEST_IMAGE_CAPTURE_TWO && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageTwo.setImageBitmap(imageBitmap);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = shre.edit();
edit.putString("image_two", encodedImage);
edit.commit();
}
Instead I'd like to store this image to the SD card and the url to the file path in shared preferences, so that I can load the images using the filepath and I'm able to attach these photos with the ACTION_SEND intent. It appears I can't do that with the way I'm currently storing the images.
This will return file name of saved image in sdcard so now you can save it in shared preferences or you can modify as you need.
public static String saveImage(Bitmap imageBitmap) {
File sdCardDirectory = Environment.getExternalStorageDirectory();
File dir = new File(sdCardDirectory + "/Folder_Name");
dir.mkdir();
String fileName = "image" + System.currentTimeMillis() + ".jpeg";
File image = new File(dir, fileName);
fileName = image.getPath();
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
fileName = Constants.ERROR_IMAGE_SAVING;
e.printStackTrace();
} catch (IOException e) {
fileName = Constants.ERROR_IMAGE_SAVING;
e.printStackTrace();
}
return fileName;
}
There is solution:
public static String saveEncodedImage(String folderName, String imgFileName, String encodedImage) {
//check sdcard is available
String sdStatus = Environment.getExternalStorageState();
if(!sdStatus.equals(Environment.MEDIA_MOUNTED)){
// sdcard not avaliable
return "";
}
String urlToPath = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator
+ folderName;
File folder = new File(urlToPath);
if (!folder.exists()){
folder.mkdir();
}
urlToPath = urlToPath + File.separator + imgFileName;
File imgFile = new File(urlToPath);
try {
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(imgFile));
bufferedWriter.write(encodedImage);
bufferedWriter.flush();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
return "";
}
return urlToPath;
}
You can use it like this:
if (requestCode == REQUEST_IMAGE_CAPTURE_TWO && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageTwo.setImageBitmap(imageBitmap);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String encodedImage = Base64.encodeToString(b, Base64.DEFAULT);
//save to sdcard
String urlToImage = saveEncodedImage("images","image_two",encodedImage);
SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = shre.edit();
edit.putString("image_two", urlToImage);
edit.commit();
}

download images from FTP :Caused by: java.lang.OutOfMemoryError

at com.example.newpingziyi.stir.CheckSdcard$LoadImagesFromSDCard.doInBackground(CheckSdcard.java:316)
error lines was make Stronger!
First.show that's error like java.lang.OutOfMemoryError!
this's code...
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
#Override
protected Object doInBackground(Object... params) {
Bitmap newBitmap = null;
File file = new File(localPath);
String[] filepath = file.list();
for (String str : filepath) {
String filename = str;
String imagePath = localPath + "/" + filename;
File files = new File(imagePath);
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
//this line was wrong!
Bitmap bitmap = BitmapFactory.decodeStream(bis);//this lines was wrong!!
is.close();
bis.close();
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,
true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
}
}
return null;
}
#Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
#Override
protected void onPostExecute(Object result) {
imageAdapter.notifyDataSetChanged();
}
}
Bitmap bitmap = BitmapFactory.decodeStream(bis);//this lines was wrong!!
now i make change below code.still OutOfMemoryError yet!
class LoadImagesFromSDCard extends AsyncTask<Object, LoadedImage, Object> {
#Override
protected Object doInBackground(Object... params) {
Bitmap newBitmap = null;
File file = new File(localPath);
String[] filepath = file.list();
for (String str : filepath) {
String filename = str;
String imagePath = localPath + "/" + filename;
File files = new File(imagePath);
FileInputStream is = null;
BufferedInputStream bis = null;
try {
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
bis.mark(0);
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
BitmapFactory.decodeStream(bis, null, opts);
int sizes = (opts.outWidth * opts.outHeight);
if (sizes > 1024 * 1024 * 4) {
int zoomRate = 2;
if (zoomRate <= 0)
zoomRate = 1;
opts.inSampleSize = zoomRate;
}
opts.inJustDecodeBounds = false;
bis.reset();
//this line was wrong!
Bitmap bitmap = BitmapFactory.decodeStream(bis, null, opts);//this lines was wrong!!
is.close();
bis.close();
if (bitmap != null) {
newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70,
true);
bitmap.recycle();
if (newBitmap != null) {
publishProgress(new LoadedImage(newBitmap));
}
}
} catch (IOException e) {
}
}
return null;
}
#Override
public void onProgressUpdate(LoadedImage... value) {
addImage(value);
}
#Override
protected void onPostExecute(Object result) {
imageAdapter.notifyDataSetChanged();
}
}
Bitmap bitmap = BitmapFactory.decodeStream(bis, null, opts);//this lines!
Here is my working code for downloading Bitmap, maybe it will help :
private Bitmap downloadBitmap(String url) {
// Getting the url from the html
url = url.substring(url.indexOf("src=\"") + 5, url.length() - 1);
url = url.substring(0, url.indexOf("\""));
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
//check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode +
" while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that android understands
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while" +
" retrieving bitmap from " + url + e.toString());
}
return null;
}

Categories

Resources