Converting images to bytes array - java

I just want to ask, I have an application like Meme Generator.
So after taking a picture, the picture will be send to second activity,
My question is that, I'm having Incompatible types on Second Activity Like
Required byte
found java.lang.object
can you help me? or suggest another kind of method for doing this?
First Activity:
FileIOManager fiom = new FileIOManager(this);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
byte[] byteArray = stream.toByteArray();
fiom.write("name",byteArray);
FileIOManager Class:
public class FileIOManager {
private Context context;
public FileIOManager(Context context) {
// TODO Auto-generated constructor stub
this.context = context;
}
public void write(String filename, Object file) {
try {
FileOutputStream fos = context.openFileOutput(filename,
Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(file);
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public Object read(String filename) {
Object object = null;
try {
FileInputStream fis = context.openFileInput(filename);
ObjectInputStream is = new ObjectInputStream(fis);
object = is.readObject();
is.close();
} catch (FileNotFoundException e) {
} catch (StreamCorruptedException e) {
} catch (IOException e) {
} catch (ClassNotFoundException e) {
}
return object;
}
and lastly Second Activity
imageView = (ImageView) findViewById(R.id.imageView2);
//byte[] byteArray = fiom.read("name");
byte[] byteArray = fiom.read("name");
Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
imageView.setImageBitmap(bmp);

Try this one, hope it will help...
public byte[] bitmapToByteArray(Bitmap bitmap)
{
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;
}
Bitmap bmp = BitmapFactory.decodeFile(file.getAbsolutePath());
byte[] bitmapBytes = bitmapToByteArray(bmp);

Related

Error in passing arraylist in another activity

Here is my declaration
List lstProfilePicture = new ArrayList();
This is my code for calling another activity
Intent i = new Intent(LogoActivity.this, MenuActivity.class);
i.putExtra("Profile", (Serializable) lstProfilePicture);
This is my Profile Class
public class Profile implements Serializable
{
private Long employeeCode;
private Bitmap employeePicture;
public Profile() {
}
public Profile(Long employeeCode, Bitmap employeePicture) {
this.employeeCode = employeeCode;
this.employeePicture = employeePicture;
}
public Long getEmployeeCode() {
return employeeCode;
}
public void setEmployeeCode(Long employeeCode) {
this.employeeCode = employeeCode;
}
public Bitmap getEmployeePicture() {
return employeePicture;
}
public void setEmployeePicture(Bitmap employeePicture) {
this.employeePicture = employeePicture;
}
}
Here is my error message
/AndroidRuntime: FATAL EXCEPTION: main
Process: oras.liv.com.oras, PID: 21484
java.lang.RuntimeException: Parcelable encountered IOException writing serializable object
How to I pass with a bitmap in class? Is there another way?
Convert it to a Byte array
Activity 1:
try {
//Write file
String filename = "bitmap.png";
FileOutputStream stream = this.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
bmp.recycle();
//Pop intent
Intent in1 = new Intent(this, Activity2.class);
in1.putExtra("image", filename);
startActivity(in1);
} catch (Exception e) {
e.printStackTrace();
}
In Activity 2, load up the bitmap:
Bitmap bmp = null;
String filename = getIntent().getStringExtra("image");
try {
FileInputStream is = this.openFileInput(filename);
bmp = BitmapFactory.decodeStream(is);
is.close();
} catch (Exception e) {
e.printStackTrace();
}

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();
}

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

Getting bitmap as null

I am trying to download the image from url and save it in a file. But it's not getting saved. So as I debug the code I found that bitmap is always null.
code:
public class ImageUserTask extends AsyncTask<Void, Void,String> {
String strURL, imageprofile;
Bitmap mBitmap = null;
Context mContext;
private File profileFile;
public ImageUserTask(Context context, String url) {
this.strURL = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected String doInBackground(Void... params) {
Bitmap bitmap = null;
File directory = null;
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
// InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream()); //This bitmap is null always
directory = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/Profile");
if (!directory.exists() && !directory.isDirectory()) {
directory.mkdirs();
}
File mypath = new File(dir,"ProfileImage");
saveFile(mypath, bitmap);
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return directory.getAbsolutePath();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
imageprofile = result;
}
}
private void saveFile(File fileName, Bitmap bmp) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(fileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); // 100 will be ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
EDIT:
public class ImageUserTask extends AsyncTask<Void,Void,Bitmap> {
String strURL, imageprofile;
Bitmap mBitmap = null;
Context mContext;
private File profileFile;
public ImageUserTask(Context context, String url) {
this.strURL = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected Bitmap doInBackground(Void... params) {
getImageFromUrl(strURL);
return mBitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null) {
Bitmap bitmap = result;
}
}
public Bitmap getImageFromUrl(String urlString) {
try {
URL url = new URL(urlString);
try {
if(mBitmap!=null) {
mBitmap.recycle();
mBitmap=null;
}
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
//Connected to server
connection.connect();
//downloading image
InputStream input = connection.getInputStream();
mBitmap = BitmapFactory.decodeStream(input);
convertBitmapToFile(mBitmap, urlString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return mBitmap;
}
public File convertBitmapToFile(Bitmap bitmap, String fileName) {
ContextWrapper cw = new ContextWrapper(mContext);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath;
}
}
What can be the reason? I have added Internet permissions too. Please help. Thank you..
class DownloadFile extends AsyncTask<String, Integer, String> {
String strFolderName;
String shareType;
String downloadPath = "";
Activity mContext;
public DownloadFile(Activity mContext) {
this.mContext = mContext;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
String fileName = "your filename with ext";
Log.d("TAG", fileName);
URL url = new URL("your url");
URLConnection conexion = url.openConnection();
conexion.connect();
String PATH = "your Path you want to store" + "/";
downloadPath = PATH + fileName;
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(downloadPath);
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String path) {
super.onPostExecute(path);
}
}
This code is work for me
Use the below methods
public Bitmap getImageFromUrl(String urlString) {
Bitmap bmp = null;
try {
URL url = new URL(urlString);
try {
if(bmp!=null) {
bmp.recycle();
bmp=null;
}
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
convertBitmapToFile(bmp, urlString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return bmp;
}
public File convertBitmapToFile(Bitmap bitmap, String fileName) {
ContextWrapper cw = new ContextWrapper(activityRef.getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath;
}
Add android Permissions for internet and Storage
Please try this
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;
}
}

Android copy file from internal storage to external

I am trying to Copy file from internal memory card to external memory card
By googling i found this answer
try {
InputStream in = new FileInputStream("/storage/sdcard1/bluetooth/file7.zip"); // Memory card path
File myFile = new File("/storage/sdcard/"); //
OutputStream out = new FileOutputStream(myFile);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
session.showToast("file copied sucessfully");
} catch (FileNotFoundException e) {
showToast(e.getMessage());
e.printStackTrace();
} catch (IOException e) {
showToast(e.getMessage());
e.printStackTrace();
}
its work for internal move to internal or external storage to external
but cross transferring do not work its throws an error Erofs read only file system
Try some thing like this:
new FileAsyncTask().execute(files);
and
// AsyncTask for Background Process
private class FileAsyncTask extends AsyncTask<ArrayList<String>, Void, Void> {
ArrayList<String> files;
ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog = ProgressDialog.show(ActivityName.this, "Your Title", "Loading...");
}
#Override
protected Void doInBackground(ArrayList<String>... params) {
files = params[0];
for (int i = 0; i < files.size(); i++) {
copyFileToSDCard(files.get(i));
} return null;
}
#Override
protected void onPostExecute(Void result) {
dialog.dismiss();
}
}
// Function to copy file to the SDCard
public void copyFileToSDCard(String fileFrom){
AssetManager is = this.getAssets();
InputStream fis;
try {
fis = is.open(fileFrom);
FileOutputStream fos;
if (!APP_FILE_PATH.exists()) {
APP_FILE_PATH.mkdirs();
}
fos = new FileOutputStream(new File(Environment.getExternalStorageDirectory()+"/MyProject", fileFrom));
byte[] b = new byte[8];
int i;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fos.close();
fis.close();
}
catch (IOException e1) {
e1.printStackTrace();
}
}
public static boolean copyFile(String from, String to) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(from);
if (oldfile.exists()) {
InputStream inStream = new FileInputStream(from);
FileOutputStream fs = new FileOutputStream(to);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread;
fs.write(buffer, 0, byteread);
}
inStream.close();
fs.close();
}
return true;
} catch (Exception e) {
return false;
}
}
Try this, Replace this line:
File myFile = new File("/storage/sdcard/");
with:
ContextWrapper cw = new ContextWrapper(getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File myFile = cw.getDir("imageDir", Context.MODE_PRIVATE);
Check this link, may be helpfull: click here

Categories

Resources