Save drawable into parse - java

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);
...

Related

image path from android to php web interface

I have an android app that captures images and sends them to firebase storage. In my web interface I retrieve the url of these images and make it like a video, but this way the image transitions are too slow. What would be the best way for me to pass the url of these images from the android app to the php web interface?
Would it be faster via socket?
Screenshot.java
private class ImageAvailableListener implements ImageReader.OnImageAvailableListener {
#Override
public void onImageAvailable(ImageReader reader) {
FileOutputStream fos = null;
Bitmap bitmap = null;
try (Image image = mImageReader.acquireLatestImage()) {
if (image != null) {
Image.Plane[] planes = image.getPlanes();
ByteBuffer buffer = planes[0].getBuffer();
int pixelStride = planes[0].getPixelStride();
int rowStride = planes[0].getRowStride();
int rowPadding = rowStride - pixelStride * mWidth;
// create bitmap
bitmap = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.ARGB_8888);
bitmap.copyPixelsFromBuffer(buffer);
IMAGES_PRODUCED++;
Log.e(TAG, "captured image: " + IMAGES_PRODUCED);
//TRANSFOMAR BITMAP EM ARRAY DE BYTES
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, baos);
byte[] dadosImagem = baos.toByteArray();
//criar nome unico de imagem
//String nomeImagem = UUID.randomUUID().toString();
StorageReference imagemRef = storageReference
.child("imagens")
.child("screenshot")
.child(idUser)
.child(IMAGES_PRODUCED+".jpeg");
//fazer upload da imagem
UploadTask uploadTask = imagemRef.putBytes(dadosImagem);
uploadTask.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//em versoes anteriores do a gente recuperava assim taskSnapshot.getDownloadUrl();
//recuperar a url para inserir no realtime
imagemRef.getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
#Override
public void onComplete(#NonNull Task<Uri> task) {
//aqui temos a url da imagem
String url = task.getResult().toString();
Log.d("TAG", IMAGES_PRODUCED + url);
//grava a url recuperada da imagem no realtime
Imagem imagem = new Imagem();
imagem.setUrl(url);
imagem.setIdUsuario(idUser);
imagem.salvarImagem();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("message", url);
jsonObject.put("byServer", false);
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

How to share image with a button? [duplicate]

This question already has answers here:
How to use "Share image using" sharing Intent to share images in android?
(17 answers)
Closed 2 years ago.
I am making QR code generator
So far I made a generator button and save button.
It works fine.
I am trying to work on the sharing button.
It takes a few days to figure out as a beginner and still I cannot make it work.
At this code, if I click share, then the app closes.
/**Barcode share*/
findViewById(R.id.share_barcode).setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(),R.id.qr_image);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
});
I guessed the problem was path.
I use savepath to save qr code image. And then maybe it conflicts with String path
So I tried String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";;
It's not working. So maybe it's different problem and I don't know how to fix it.
Could you show me how to fix?
MainActivity
public class MainActivity extends AppCompatActivity {
private String inputValue;
private String savePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + "/Camera/";
private Bitmap bitmap;
private QRGEncoder qrgEncoder;
private ImageView qrImage;
private EditText edtValue;
private AppCompatActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
qrImage = findViewById(R.id.qr_image);
edtValue = findViewById(R.id.edt_value);
activity = this;
/**Barcode Generator*/
findViewById(R.id.generate_barcode).setOnClickListener(view -> {
inputValue = edtValue.getText().toString().trim();
if (inputValue.length() > 0) {
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
qrgEncoder = new QRGEncoder(
inputValue, null,
QRGContents.Type.TEXT,
smallerDimension);
qrgEncoder.setColorBlack(Color.BLACK);
qrgEncoder.setColorWhite(Color.WHITE);
try {
bitmap = qrgEncoder.getBitmap();
qrImage.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
}
} else {
edtValue.setError(getResources().getString(R.string.value_required));
}
});
/**Barcode save*/
findViewById(R.id.save_barcode).setOnClickListener(v -> {
String filename = edtValue.getText().toString().trim();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
try {
ContentResolver resolver = getContentResolver();
ContentValues contentValues = new ContentValues();
contentValues.put(MediaStore.MediaColumns.DISPLAY_NAME, filename + ".jpg");
contentValues.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpg");
contentValues.put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DCIM);
Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
OutputStream fos = resolver.openOutputStream(Objects.requireNonNull(imageUri));
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
Objects.requireNonNull(fos).close();
Toast toast= Toast.makeText(getApplicationContext(),
"Image Saved. Check your gallery.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.TOP|Gravity.CENTER_HORIZONTAL, 0, 0);
toast.show();
edtValue.setText(null);
} catch (IOException e) {
e.printStackTrace();
}
} else {
if (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
try {
boolean save = new QRGSaver().save(savePath, filename, bitmap, QRGContents.ImageType.IMAGE_JPEG);
String result = save ? "Image Saved. Check your gallery." : "Image Not Saved";
Toast.makeText(activity, result, Toast.LENGTH_LONG).show();
edtValue.setText(null);
} catch (Exception e) {
e.printStackTrace();
}
} else {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
}
}
});
/**Barcode share*/
findViewById(R.id.share_barcode).setOnClickListener(v -> {
Bitmap b = BitmapFactory.decodeResource(getResources(),R.id.qr_image);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(getContentResolver(), b, "Title", null);
Uri imageUri = Uri.parse(path);
share.putExtra(Intent.EXTRA_STREAM, imageUri);
startActivity(Intent.createChooser(share, "Select"));
});
}
}
I think you can solve this by:
Saving the bitmap in a file.
Then sharing the URI of that file in the intent.
In the code below, I am saving the image at the app level directory, you can choose your own and the code is written in kotlin.
Note: If you are using an app-level directory for saving the image then you must use the file provide to get the URI else it may result in FileUriExposedException
try {
val file = File(getExternalFilesDir(null),System.currentTimeMillis().toString() + ".png")
file.createNewFile()
val b = imageView.drawable.toBitmap()
FileOutputStream(file).use { out ->
b.compress(Bitmap.CompressFormat.PNG, 100, out)
}
val share = Intent(Intent.ACTION_SEND)
share.type = "image/jpeg"
val photoURI = FileProvider.getUriForFile(this, applicationContext.packageName.toString() + ".provider", file)
share.putExtra(Intent.EXTRA_STREAM, photoURI)
startActivity(Intent.createChooser(share, "Share Image"))
Toast.makeText(this, "Completed!!", Toast.LENGTH_SHORT).show()
} catch (e: IOException) {
e.printStackTrace()
Toast.makeText(this, e.message, Toast.LENGTH_SHORT).show()
}
In JAVA:
public void shareImage(Activity activity, ImageView imageView) {
try {
File file = new File(activity.getExternalFilesDir(null), System.currentTimeMillis() + ".png");
file.createNewFile();
Bitmap bitmap = drawableToBitmap(imageView.getDrawable());
FileOutputStream fOut = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
Intent share = new Intent("android.intent.action.SEND");
share.setType("image/jpeg");
Uri photoURI = FileProvider.getUriForFile(activity,activity.getPackageName(), file);
share.putExtra("android.intent.extra.STREAM", photoURI);
activity.startActivity(Intent.createChooser(share, "Share Image"));
} catch (Exception var14) {
}
}
public static Bitmap drawableToBitmap (Drawable drawable) {
Bitmap bitmap;
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
if(bitmapDrawable.getBitmap() != null) {
return bitmapDrawable.getBitmap();
}
}
if(drawable.getIntrinsicWidth() <= 0 || drawable.getIntrinsicHeight() <= 0) {
bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ARGB_8888); // Single color bitmap will be created of 1x1 pixel
} else {
bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
}
Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}

How can I take Screenshots using Arcore?

I am trying to take a screenshot of my Augmented Reality Screen and pass it as a bitmap to another activity.
This is the code that I am using to take the screenshot:
Function to take screen shot
public static void tmpScreenshot(Bitmap bmp, Context context){
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bmp.recycle();
//Pop intent
Intent in1 = new Intent(context, CostActivity.class);
in1.putExtra("image", filename);
context.startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
}
Function to receive screenshot
private void loadTmpBitmap() {
Bitmap bmp = null;
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
ImageView imageView = findViewById(R.id.test);
imageView.setImageBitmap(Bitmap.createScaledBitmap(bmp, 120, 120, false));
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Even though the Screenshot was taken, it was black when it is passed to another activity.
In addition, the Screenshot only appeared after I pressed the back button
Can anyone help me with the code to take a screenshot with ARCore? Or what am I doing wrong?
It is not possible to take a screenshot of a SurfaceView using your method. If you do then the screenshot will be black, as it only works for regular views.
What you need to use is pixelcopy.
private void takePhoto() {
ArSceneView view = arFragment.getArSceneView();
// Create a bitmap the size of the scene view.
final Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
Bitmap.Config.ARGB_8888);
// Create a handler thread to offload the processing of the image.
final HandlerThread handlerThread = new HandlerThread("PixelCopier");
handlerThread.start();
// Make the request to copy.
PixelCopy.request(view, bitmap, (copyResult) -> {
if (copyResult == PixelCopy.SUCCESS) {
try {
saveBitmapToDisk(bitmap);
} catch (IOException e) {
Toast toast = Toast.makeText(VisualizerActivity.this, e.toString(),
Toast.LENGTH_LONG);
toast.show();
return;
}
SnackbarUtility.showSnackbarTypeLong(settingsButton, "Screenshot saved in /Pictures/Screenshots");
} else {
SnackbarUtility.showSnackbarTypeLong(settingsButton, "Failed to take screenshot");
}
handlerThread.quitSafely();
}, new Handler(handlerThread.getLooper()));
}
public void saveBitmapToDisk(Bitmap bitmap) throws IOException {
// String path = Environment.getExternalStorageDirectory().toString() + "/Pictures/Screenshots/";
if (videoDirectory == null) {
videoDirectory =
new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/Screenshots");
}
Calendar c = Calendar.getInstance();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH.mm.ss");
String formattedDate = df.format(c.getTime());
File mediaFile = new File(videoDirectory, "FieldVisualizer"+formattedDate+".jpeg");
FileOutputStream fileOutputStream = new FileOutputStream(mediaFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fileOutputStream);
fileOutputStream.flush();
fileOutputStream.close();
}

Resizing image file rotate it horizontally android

Hey I have an app that choose an image from the gallery , resizing it and uploading it to ftp server , but I have notice that in some photo's the app flips the image horizontally and upload it backwards, I can't figure out why it is happening (It only happened on some photos and on others not, usually happened on photos taken from my camera)
Here is the code for the resize part:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK&&data!=null) {
selectedImageURI = data.getData();
showUri = data.getData();
imagePath = RealPathUtil.getPath(this,data.getData());
loadedImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
//loadedImage.setImageURI(data.getData());
Glide.with(this).load(data.getData())
.into((ImageView) findViewById(R.id.upload_image1));
ImageView m =(ImageView)findViewById(R.id.remove_image);
m.setFocusable(true);
m.setVisibility(View.VISIBLE);
File file = new File(RealPathUtil.getPath(this,data.getData()));
Bitmap bitmap = decodeFile(file);
ImageResizer(bitmap);
}
}
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
final int REQUIRED_SIZE=200;
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_SIZE && o.outHeight/scale/2>=REQUIRED_SIZE)
scale*=2;
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
Bitmap bit1 = BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
//Matrix matrix = new Matrix();
//matrix.postRotate(45);
// Bitmap rotatedBitmap = Bitmap.createBitmap(bit1 , 0, 0, bit1 .getWidth(), bit1 .getHeight(), matrix, true);
return bit1;
} catch (FileNotFoundException e) {}
return null;
}
private void ImageResizer(Bitmap bitmap) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/Pic");
if(!myDir.exists()) myDir.mkdirs();
String fname = "resized.png";
File file = new File (myDir, fname);
if (file.exists()){
file.delete();
Log.d("exist","replace");
SaveResized(file, bitmap);
} else {
SaveResized(file, bitmap);
Log.d("saved","now");
}
selectedImageURI = Uri.fromFile(file);
imagePath = RealPathUtil.getPath(this,selectedImageURI);
}
private void SaveResized(File file, Bitmap bitmap) {
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
can someone help me and tell me why is it happening?

How to convert Uri image into Base64?

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

Categories

Resources