Load image as a File - java

How can I load an image ".jpg for example" as a File ?
To be precise this file was saved using :
public static void saveFile(Context context, Bitmap bitmap, String picName) {
FileOutputStream fileOutputStream;
try {
fileOutputStream = context.openFileOutput(picName, Context.MODE_PRIVATE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 30, fileOutputStream);
fileOutputStream.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "file not found");
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "io exception");
e.printStackTrace();
}
}
So I only have the name as reference
I tried that :
public static Bitmap loadBitmap(Context context, String picName) {
Bitmap bitmap = null;
FileInputStream fileInputStream;
try {
fileInputStream = context.openFileInput(picName);
bitmap = BitmapFactory.decodeStream(fileInputStream);
fileInputStream.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "file not found");
e.printStackTrace();
} catch (IOException e) {
Log.d(TAG, "io exception");
e.printStackTrace();
}
return bitmap;
}
It works but I need it to be a file

If you wish to work with File objects, I recommend that you do so consistently. Use getFilesDir() or getCacheDir() as the base for building a File of where you want the file to go (e.g., new File(getCacheDir(), picName)). Then, use FileOutputStream and FileInputStream for your I/O, replacing openFileOutput() and openFileInput().

Related

how to send text file created from android studio

i have saved some data in a .txt in the app file directory using this way, the name is in FILE_NAME variable which is string.
public void save()
{
mEditText = findViewById(R.id.data);
String text = mEditText.getText().toString();
FileOutputStream fos = null;
try {
fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
fos.write(output.getBytes());
Toast.makeText(this, "Saved to " + getFilesDir() + "/" + FILE_NAME,
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Now i want to get the data from this .txt file and i'm trying to find a way to do it. It has a lot of lines of information in so it will be convenient if i can send the file directly to my email, upload it on google drive or any other way to get it completely.

Android: Saving .png from URL into app internal storage

I'm relatively new to android, and I'm trying to modify an android app such that it downloads a profile picture (preferably in PNG) from a URL, and saves it in the com.companyName.AppName.whatever/files. It should be noted that the app was initially created in Unity, and just built and exported.
Here's my initial code:
URL url = null;
try {
url = new URL(playerDO.getProfileURL());
} catch (MalformedURLException e) {
e.printStackTrace();
}
InputStream input = null;
try {
input = url.openStream();
} catch (IOException e) {
e.printStackTrace();
}
String fileName = playerDO.getId() + ".png";
FileOutputStream outputStream = null;
try {
outputStream = openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = new byte[256];
int bytesRead = 0;
while ((bytesRead = input.read(buffer, 0, buffer.length)) >= 0) {
outputStream.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT: Here's my other code, as suggested by #Ashutosh Sagar
InputStream input = null;
Bitmap image = null;
try {
input = url.openStream();
image = BitmapFactory.decodeStream(input);
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String fileName = playerDO.getId() + ".png";
FileOutputStream outputStream = null;
File myDir = getFilesDir();
try {
Log.wtf("DIRECTORY", myDir.toString());
File imageFile = new File(myDir, fileName);
if (!imageFile.exists()){
imageFile.createNewFile();
Log.wtf("ANDROID NATIVE MSG: WARN!", "File does not exist. Writing to: " + imageFile.toString());
}
outputStream = new FileOutputStream(imageFile, false);
image.compress(Bitmap.CompressFormat.PNG, 90, outputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
Log.wtf("AWWW CRAP", e.toString());
}
}
(It doesn't write either).
Unfortunately, I've had several problems with this. My primary issue is that when it (on the cases that it does) runs, it actually doesn't save anything. I'll go and check com.companyName.AppName.whatever/files directory only to find no such .png file. I will also need it to overwrite any existing files of the same name, which is hard to check when it doesn't work.
My secondary issue is that it fails to take into account delays in internet connection. Although I've put in enough try-catch clauses to stop it from crashing (as it used to), the end result is that it also doesn't save.
How can I improve upon this? Anything I'm missing?
EDIT:
Printing out the directory reveals it should be in:
/data/user/0/com.appName/files/5965e9e4a0f0463853016e2b.png
However, using ES File explorer, the only thing remotely close to that is
emulated/0/Android/data/com.appName/files/
Are they the same directory?
try this first get bitmap image from url
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.d("Error", e.getStackTrace().toString());
}
and to save bitmap image please check the ans of GoCrazy
Try this
void getImage(String string_url)
{
//Generate Bitmap from URL
URL url_value = new URL(string_url);
Bitmap image =
BitmapFactory.decodeStream(url_value.openConnection().getInputStream());
//Export File to local Directory
OutputStream stream = new FileOutputStream("path/file_name.png");
/* Write bitmap to file using JPEG or PNG and 80% quality hint for JPEG. */
bitmap.compress(CompressFormat.PNG, 80, stream);
stream.close();
}

Saving ad retrieving images from MS SQL Server using Hibernate - using the image type

I am using Hibernate. I have mapped my column nIcon VARBINARY(MAX) in my object as the following
#Column(columnDefinition="binary")
public byte[] getNicon() {
return this.nicon;
}
The method getByteArrayFromFile() is used to get the bytes from an image file, which I successfully write to the database.
public static byte[] getByteArrayFromFile(String absoluteFilePath) {
byte [] byteArray = null;
File file = new File(absoluteFilePath);
byteArray = new byte[(int) file.length()];
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(file);
fileInputStream.read(byteArray);
} catch (FileNotFoundException e) {
logger.error(getStackTrace(e));
e.printStackTrace();
} catch (IOException e) {
logger.error(getStackTrace(e));
e.printStackTrace();
}finally {
if(fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
logger.error(getStackTrace(e));
e.printStackTrace();
}
}
}
return byteArray;
}
The method getFileFromByteArray() is used to write the image file from the byte array that I retrieve from the database.
public static boolean getFileFromByteArray(String fileName, byte [] byteArray) {
boolean isSuccessful = false;
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(fileName);
fileOutputStream.write(byteArray);
isSuccessful = true;
} catch (FileNotFoundException e) {
logger.error(getStackTrace(e));
e.printStackTrace();
} catch (IOException e) {
logger.error(getStackTrace(e));
e.printStackTrace();
} finally {
if (fileOutputStream !=null) {
try {
fileOutputStream.close();
} catch (IOException e) {
logger.error(getStackTrace(e));
e.printStackTrace();
}
}
}
return isSuccessful;
}
My problem is that I am using binary to store the file. I would like to use the IMAGE type in MS SQL Server.
I know that the Hibernate mapping #LOB can be used to store the image as IMAGE type.
BUT I am having problems while writing the bytes back to file.

Writing/Reading gif internal storage

I'm trying to load a gif from a url to be displayed in an Imageview, store it in the internal storage and then later read it again. But it refuses to either store the image or reading it, not sure which one because I get no exceptions. Loading the image to the imageview works. The first method below (loadImage())
public Bitmap loadImage(String url){
Bitmap bm = null;
URL request;
try {
if(url!=null){
request = new URL(url);
InputStream is = request.openStream();
bm = BitmapFactory.decodeStream(is);
is.close();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bm;
}
public String writeGifToInternalStorage (Bitmap outputImage) {
try {
String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
ByteBuffer byteBuffer = ByteBuffer.allocate(outputImage.getByteCount());
outputImage.copyPixelsToBuffer(byteBuffer);
byteBuffer.flip();
byte[] data = new byte[byteBuffer.limit()];
byteBuffer.get(data);
FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
fos.write(data);
fos.close();
return fileName;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public Bitmap readFileFromInternalStorage(String filename) {
if (filename == null) return null;
FileInputStream fis;
try {
fis = ctx.openFileInput(filename);
return BitmapFactory.decodeStream(fis);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
Any ideas of whats wrong?
Your method readFileFromInternalStorage read an encoded image from the file system. This image file should be what you receive from the server.
For that, you need to save the image when you receive it from the server, for example like so:
InputStream is = new BufferedInputStream(request.openStream());
String fileName = String.valueOf(Calendar.getInstance().getTimeInMillis());
FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
byte[] buffer = new byte[1024];
int red = 0;
while ((red = is.read(buffer)) != -1) {
fos.write(buffer,0, red);
}
fos.close();
is.close();
Then, your image is saved to the disk, and you can open it using your readFileFromInternalStorage method.
Also, if you use HttpClient instead of URL, I wrote a one-liner for downloading a file: Android download binary file problems

How to overwrite a file if it already exists in dropbox?

I am uploading a file in dropbox by this method:
public void upload() {
FileInputStream inputStream = null;
try {
File file = new File(Environment.getExternalStorageDirectory()
.toString() + "/write.txt");
inputStream = new FileInputStream(file);
Entry newEntry = mDBApi.putFile("/write.txt", inputStream,
file.length(), null, null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev);
} catch (DropboxUnlinkedException e) {
// User has unlinked, ask them to link again here.
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
but when already this file exists in the folder then the file get renamed to write(1).txt
but I want that if the file already exists in the dropbox share folder then it will be replaced. What should I do now?
You can use mDBApi.putFileOverwrite instead of mDBApi.putFile

Categories

Resources