I have a camera record intent, when the result is ok, i try to convert this video to byte[] to send a webservice:
Im doing this:
if (resultCode == RESULT_OK) {
// Video guardado
videoUri = data.getData();
if (videoUri != null) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
FileInputStream fichero_codificar = null;
try {
fichero_codificar = new FileInputStream(
videoUri.getPath());
byte[] buf = new byte[1024];
int n;
while (-1 != (n = fichero_codificar.read(buf))) {
out.write(buf, 0, n);
}
byte[] videoByte = out.toByteArray();
strBase64 = Base64.encode(videoByte);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
But in fichero_codificar = new FileInputStream(
videoUri.getPath())
logcat say me the file is not exists or the patch isnt propertly.
Anyone have a example for my qustion please?
thanks
Looks like you're finding the information incorrectly. Here is how I used the Camera intent in my application:
thumbnail = (Bitmap) data.getExtras().get("data");
try {
FileOutputStream out = new FileOutputStream(getPicName(index));
thumbnail.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
So maybe try something along those lines with a Video object rather than a Bitmap object. If that doesn't work, you could try .getAbsolutePath() instead.
Yeah it's definitely not doing what you think it does. I ran the debugger on mine and getPath returned this: /external/images/media/21 , which is a content Uri.
Related
I need to save the .svg in the Internal storage of android application and retrieve it and set it to the ImageView.
I am not able to save the .svg file. i am using this method -
File cacheDir = ctx.getCacheDir();
f = new File(cacheDir, name + ".png");
try {
InputStream in = new java.net.URL(imageurl).openStream();
mIcon = BitmapFactory.decodeStream(in);
try {
FileOutputStream out = new FileOutputStream(
f);
mIcon.compress(
Bitmap.CompressFormat.JPEG,
100, out);
out.flush();
out.close();
return f;
} catch (FileNotFoundException e) {
return null;
} catch (IOException e) {
return null;
}
} catch (Exception e) {
return null;
}
Why are you decoding SVG into bitmap ? I'm not sure it is possible.
But if you want to save the SVG file to storage, just copy you input stream to the output stream.
Simple java solution :
byte[] buffer = new byte[1024];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
or with IOUtils
If you want to display your SVG file, look at https://github.com/pents90/svg-android/tree/master/svgandroid
I am doing an android app which involves a concept where I have to extract numbers from the captured image. Can you please help me or guide me a link where I could find the appropriate tutorials?
You have a good tutorial here where is explains method to create, to reading and writting files, in your case needs to read.
When you read this tutorial try my code that return a string of bytes:
public String formatPhoto_JPEGtoByteArray (String uri){
// Read bitmap from file
Bitmap bitmap = null;
InputStream stream = null;
ByteArrayOutputStream byteStream = null;
try {
stream = new BufferedInputStream(new FileInputStream(new File(uri)));
bitmap = BitmapFactory.decodeStream(stream);
byteStream = new ByteArrayOutputStream();
Matrix matrix = new Matrix();
bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteStream);
// Convert ByteArrayOutputStream to byte array. Close stream.
byte[] byteArray = byteStream.toByteArray();
Log.e("-- FilesAndFolders.formatPhoto_JPEGtoByteArray --", "Last file of size: " + byteArray.length);
String imageEncoded = Base64.encodeToString(byteArray, Base64.NO_WRAP);
byteStream.close();
byteStream = null;
return imageEncoded;
}
catch (IOException ex) {
Log.e("-- FilesAndFolders.formatPhoto --", "Exception with " + uri,ex);
return null;
}
catch (Exception ex){
Log.e("-- FilesAndFolders.formatPhoto --", "Exception with " + uri,ex);
return null;
}
finally {
try {
if (stream != null) stream.close();
if (byteStream != null) byteStream.close();
} catch (Exception e) {}
}
}
Tell me if I helped you and good programming!
I would like the user to be able to import custom sounds in my app to change the default sounds. I already have this functionality working for bitmaps, but I would like to extend to sounds as well. The crucial step I am missing is audio decoding. I do not know what format the sound will come in, so I need to decode the audio before saving it to internal storage. For bitmaps this was accomplished by the bitmapfactory and the bitmap object, but I cannot find an analogous service for audio. This is the code that I have so far. The bitmap portions work, but the audio parts are incomplete.:
private void retrievepicture() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, 1);//retrieve picture has a code of 1
}
private void retrievesound() {
Intent intent = new Intent();
intent.setType("audio/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, 2);//retrieve sound has a code of 2
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
usingintents = false;
if (requestCode == 1 && resultCode == Activity.RESULT_OK)
try {
InputStream stream = getContentResolver().openInputStream(
data.getData());
Bitmap bitmap = BitmapFactory.decodeStream(stream);
stream.close();
File deletefile = new File(savepath);
System.out.println(String.format("Replacing file %s",deletefile.getPath()));
deletefile.delete();
saveImageToInternalStorage(bitmap,savepath);
bitmap.recycle();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (requestCode == 2 && resultCode == Activity.RESULT_OK)
{
//The code for saving audio would go here
InputStream stream = getContentResolver().openInputStream(
data.getData());
}
super.onActivityResult(requestCode, resultCode, data);
}
public boolean saveImageToInternalStorage(Bitmap image, String filepath) {
try {
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = new FileOutputStream(filepath);
// Writing the bitmap to the output stream
if(image.getWidth() >480 || image.getHeight() > 480)
image = Bitmap.createScaledBitmap(image, 480, 480, false);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
I got it to work by getting the file path from the intent, and copying the file as it is instead of decoding it. All the files that I looked at did not have a clear format(they weren't .wav or .mp3, there was no file type listed)
This is what my code looks like inside the onActivityResult for the sound portion
InputStream stream = getContentResolver().openInputStream(data.getData());
String FilePath = data.getData().getPath();
File original = new File(FilePath);
File deletefile = new File(savepath);
String newpath = deletefile.getParent() + "/" + original.getName();
deletefile.delete();
File newfile = new File(newpath);
FileOutputStream out = new FileOutputStream(newfile);
int read = 0;
byte[] bytes = new byte[1024];
while ((read = stream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.close();
stream.close();
Kotlin 1.2
fun saveAudio(myAudio:Intent?):String {//TURN ON PERSMISSIONS ON THE EMULATOR IN SETTINGS
//var bytes = ByteArrayOutputStream()
val audioURI = myAudio!!.data
try {
val audioDirectory = File(
(Environment.getExternalStorageDirectory()).toString() + AUDIO_DIRECTORY)
val out = File(audioDirectory, ("fullAudio" + ".mp3"))
if (!audioDirectory.exists()){
audioDirectory.mkdirs()
}
out.createNewFile()//cressh
val file = File(audioURI.path)
val fo = FileOutputStream(out)
//val input = FileInputStream(f)
var stream = contentResolver.openInputStream(audioURI)
var read = 0
fo.write(stream.readBytes(1024))
MediaScannerConnection.scanFile(this,
arrayOf(file.getPath()),
arrayOf("audio/mpeg"),null)
fo.close()
return file.absolutePath
}catch (e1: IOException){
e1.printStackTrace()
}
return ""
}
I thought this wouldn't be too hard but have been banging my head against a desk for the last few hours and would really appreciate some help. Essentially, I want to get an image from a url, save it to internal memory (not sd card) and be able to retrieve that image and show it using an ImageView at a later time.
This is how I get the pictures from a url and write them to memory(urls are stored in "pics"):
String urlstring = pics[l][w];
if (urlstring != null){
try {
URL url = new URL(urlstring);
InputStream input = url.openStream();
FileOutputStream output = openFileOutput(("specimage"+l) + ("" +w+".jpg"), MODE_PRIVATE);
byte[] buffer = new byte[input.available()];
int n = input.read(buffer, 0, buffer.length);
while (n >= 0) {
output.write(buffer, 0, buffer.length);
n = input.read(buffer, 0, buffer.length);
}
output.close();
input.close();
} catch (Exception e) {
GlobalState.popupMessage(homePage, "Error", "Files could not be stored on disk");
}
}
This is how I attempt to retrieve them (path is the filename):
private Bitmap getPic(String path){
FileInputStream in;
Bitmap bMap = null;
BufferedInputStream buf;
try {
in = openFileInput(path);
buf = new BufferedInputStream(in);
byte[] bMapArray= new byte[buf.available()];
buf.read(bMapArray);
bMap = BitmapFactory.decodeStream(buf);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
System.out.println("excep.");
}
if (bMap == null) System.out.println("null");
return bMap;
}
If I do this the picture does not show up, but the program does not crash. An exception is not triggered. However, the value of bMap is given as null. I also get this strange message in the log:
DEBUG/skia(19358): --- SkImageDecoder::Factory returned null
Please let me know what I'm doing wrong. I have been ransacking my brain to no avail.
I should mention I do setImageBitmap in the ui thread.
Just try this, (Replace with your) and let me know what happen,
ImageView img = (ImageView)findViewById(R.id.imgView1);
FileInputStream in;
Bitmap bMap = null;
BufferedInputStream buf;
try {
in = openFileInput("icon.png");
buf = new BufferedInputStream(in);
byte[] bMapArray= new byte[buf.available()];
buf.read(bMapArray);
bMap = BitmapFactory.decodeByteArray(bMapArray,0,bMapArray.length);
img.setImageBitmap(bMap);
if (in != null) {
in.close();
}
if (buf != null) {
buf.close();
}
} catch (Exception e) {
System.out.println("excep.");
}
I am using webview in android to display images (mainly using google ajax API), Now if I want to save an image into local storage, How do I do ? I have image url, which can be used for saving.
If you have the image url, this is dead easy. You just have to retrieve the bytes of the image. Here is a sample that should help you :
try {
URL url = new URL(yourImageUrl);
InputStream is = (InputStream) url.getContent();
byte[] buffer = new byte[8192];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
while ((bytesRead = is.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
return output.toByteArray();
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
This will return a byteArray that you can either store wherever you like, or reuse to create an image, by doing that :
Bitmap bm = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
I know this is a quite old but this is valid too:
Bitmap image = BitmapFactory.decodeStream((InputStream) new URL("Http Where your Image is").getContent());
With the Bitmap filled up, just do this to save to storage (Thanks to https://stackoverflow.com/a/673014/1524183)
FileOutputStream out;
try {
out = new FileOutputStream(filename);
image.compress(Bitmap.CompressFormat.PNG, 90, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try{
out.close();
} catch(Throwable ignore) {}
}
IHMO much more cleaner and simpler than the accepted answer.