I have an Image in web server and load it to Image View using Picasso perfectly then save it to a folder in internal storage memory every thing is OK but the problem is the saved image size is 0 byte
here is my code
File newDir=new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"km");
if (!newDir.exists()) {
if (!newDir.mkdirs()) {
Toast.makeText(this, "can not create directory", Toast.LENGTH_SHORT).show();
}
}
Picasso.with(this).load("http://192.168.1.101/cima/1.jpg").into(img);
File file = new File(new File("/storage/sdcard0/Download/km/"), "1.jpg");
img.buildDrawingCache();
Bitmap bmap = img.getDrawingCache();
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
any help for this issue ??
Try to below code
Picasso.with(getActivity())
.load(url)
.into(new Target() {
#Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
try {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/yourDirectory");
if (!myDir.exists()) {
myDir.mkdirs();
}
String name = new Date().toString() + ".jpg";
myDir = new File(myDir, name);
FileOutputStream out = new FileOutputStream(myDir);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch(Exception e){
// some action
}
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
}
);
Related
I examined similar subjects, but I couldn't do it. I'm trying to share .mp3 file with LongClick button. I found it for JPEG files. One guy created method for sharing jpeg file. How can I convert it for .mp3 files?
package com.example.tunch.trap;
import...
public class sansar extends AppCompatActivity {
private String yardik;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_sansar);
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
yardik = createImageOnSDCard(R.raw.yardik_denizi);
final MediaPlayer yardikdenizi = MediaPlayer.create(this, R.raw.yardik_denizi);
Button btnYardik = (Button) findViewById(R.id.btnSansar_1);
btnYardik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(yardikdenizi.isPlaying()){
yardikdenizi.seekTo(0);
}
yardikdenizi.start();
}
});
btnYardik.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
Uri path= FileProvider.getUriForFile(sansar.this, "com.example.tunch.trap", new File(yardik));
Intent shareYardik = new Intent();
shareYardik.setAction(Intent.ACTION_SEND);
shareYardik.putExtra(Intent.EXTRA_TEXT,"Bu ses dosyasını gönderiyorum");
shareYardik.putExtra(Intent.EXTRA_STREAM, path);
shareYardik.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareYardik.setType("audio/mp3");
startActivity(Intent.createChooser(shareYardik, "Paylas.."));
return true;
}
});
}
private String createImageOnSDCard(int resID) {
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), resID);
String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/" + resID +".mp3";
File file = new File(path);
try {
OutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
}
catch (Exception e){
e.printStackTrace();
}
return file.getPath();
}
}
This is all Java code. createImageOnSDCard method is for images. I want to use it for my audio file (yardik_denizi.mp3). When I run this, it works but program is trying to send jpeg file. So it doesn't work literally :) How should I change that last part?
You need a method that copies a private raw resource content (R.raw.yardik_denizi) to a publicly readable file such that the latter can be shared with other applications:
public void copyPrivateRawResuorceToPubliclyAccessibleFile(#RawRes int resID,
#NonNull String outputFile) {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
inputStream = getResources().openRawResource(resID);
outputStream = openFileOutput(outputFile, Context.MODE_WORLD_READABLE
| Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
try {
while ((length = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
} catch (IOException ioe) {
/* ignore */
}
} catch (FileNotFoundException fnfe) {
/* ignore */
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
/* ignore */
}
try {
outputStream.close();
} catch (IOException ioe) {
/* ignore */
}
}
}
and then:
copyPrivateRawResuorceToPubliclyAccessibleFile(R.raw.yardik_denizi, "sound.mp3");
final Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("audio/*");
Uri uri = Uri.fromFile(getFileStreamPath("sound.mp3"));
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Sound File"));
You should change the path for uri at
Uri path= FileProvider.getUriForFile(sansar.this, "com.example.tunch.trap", new File(change_it_path_to_yardik_denizi.mp3));
Finally i got the answer. I can send mp3 files to other apps with this code.
copyFiletoExternalStorage(R.raw.yardik_denizi, "yardik_denizi.mp3");
Uri path= FileProvider.getUriForFile(sansar.this,
"com.example.tunch.trap", new File(Environment.getExternalStorageDirectory() +
"/Android/data/yardik_denizi.mp3"));
Intent shareYardik = new Intent();
shareYardik.setAction(Intent.ACTION_SEND);
shareYardik.putExtra(Intent.EXTRA_TEXT,"Bu ses dosyasını gönderiyorum");
shareYardik.putExtra(Intent.EXTRA_STREAM, path);
shareYardik.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareYardik.setType("audio/mp3");
startActivity(Intent.createChooser(shareYardik, "Paylas.."));
And need to create a method to save data in external store.
private void copyFiletoExternalStorage (int resourceId, String resourceName){
String pathSDCard = Environment.getExternalStorageDirectory() + "/Android/data/"
+ resourceName;
try{
InputStream in = getResources().openRawResource(resourceId);
FileOutputStream out = null;
out = new FileOutputStream(pathSDCard);
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
In my app I have a fragment which opens the device camera and allows the users to take photos and store them in a directory inside the gallery. This is the method that I use to create the dir and save the taken image:
private void saveImage(Bitmap finalBitmap, String image_name) {
final String appDirectoryName = "/Feel/";
String root = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES).toString() + appDirectoryName;
File myDir = new File(root);
myDir.mkdirs();
String fname = "Image-" + image_name + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
Log.i("LOAD", root + fname);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Everything works fine except finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);. When it comes to this line it skips the process... The directory is not created too... What is causing this problem?
This is my CameraFragment, where I retrieve the photo that was shot:
final Button btnShoot = viewCamera.findViewById(R.id.btnShoot);
imgUltimaFoto.setVisibility(View.INVISIBLE);
btnShoot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cmrView.addCameraListener(new CameraListener() {
#Override
public void onPictureTaken(final byte[] picture) {
super.onPictureTaken(picture);
CameraUtils.decodeBitmap(picture, new CameraUtils.BitmapCallback() {
#Override
public void onBitmapReady(Bitmap bitmap) {
imgUltimaFoto.setImageBitmap(bitmap);
imgUltimaFoto.setVisibility(View.VISIBLE);
saveImage(bitmap,"imagem1");
}
});
}
});
cmrView.capturePicture();
}
});
i am try to download a image and save it locally. Everything runs trough i didnt get any exceptions, but the file dont appear in my location
i searched for an solution but didnt find any.
Heres my code:
private void saveImages() {
try{
final File thumbsPath = new File(getExternalFilesDir(null), "thumbs");
if (!thumbsPath.exists())
thumbsPath.mkdirs();
Target target = new Target(){
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
File file = new File(thumbsPath.getAbsolutePath() + "/file.jpeg"); //folder exists
try {
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, ostream);
ostream.flush();
ostream.close();
} catch (Exception e) {
Log.e("ERROR", e.getMessage());
}
}
}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
Log.e("ERROR", "");
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
Log.e("ERROR", "");
}
};
Picasso.with(getApplicationContext())
.load(myurltodownloadfrom)
.into(target);
}
catch (Exception e){
Log.e("ERROR",e.getMessage());
}
}
Never store Files that way.
It is all covered here: https://developer.android.com/training/basics/data-storage/files.html
I get a warning stating that the result of cachePath.createNewFile(); is ignored. Otherwise the following code does not save an image to my phone. What can I do?
holder.messageImage.setOnLongClickListener(v -> {
v.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY);
Bitmap bitmap = ((BitmapDrawable) holder.messageImage.getDrawable()).getBitmap();
File root = Environment.getExternalStorageDirectory();
File cachePath = new File(root.getAbsolutePath() + "/DCIM/Camera/image.jpg");
try {
FileOutputStream ostream = new FileOutputStream(cachePath);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
Toast.makeText(mContext, "Image saved successfully", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
Log.w(getClass().toString(), e);
Toast.makeText(mContext, "Failed saving image", Toast.LENGTH_SHORT).show();
}
return false;
});
I download the image from my back end this way:
private void downloadMessageImage(ViewHolder holder, int position) {
ParseQuery<ParseObject> query = new ParseQuery<>(ParseConstants.CLASS_YEET);
query.whereEqualTo(ParseConstants.KEY_OBJECT_ID, mYeets.get(position).getObjectId());
query.findInBackground((user, e) -> {
if (e == null) for (ParseObject userObject : user) {
if (userObject.getParseFile("image") != null) {
String imageURL = userObject.getParseFile("image").getUrl();
/*Log.w(getClass().toString(), imageURL);*/
if (imageURL != null) {
holder.messageImage.setVisibility(View.VISIBLE);
Picasso.with(mContext)
.load(imageURL)
.placeholder(R.color.placeholderblue)
.into(holder.messageImage);
} else {
holder.messageImage.setVisibility(View.GONE);
}
}
}
});
}
The bitmap certainly does not exist: android.graphics.Bitmap#12d9cc4
to save an image I use the following code:
try {
signature.setDrawingCacheEnabled(true);
Bitmap bm = Bitmap.createBitmap(signature.getDrawingCache());
// Define params for save
File f = new File(Environment.getExternalStorageDirectory() + "/Cassiopea/momomorez/" + File.separator + "signature.png");
f.createNewFile();
FileOutputStream os = new FileOutputStream(f);
os = new FileOutputStream(f);
//compress to specified format (PNG), quality - which is ignored for PNG, and out stream
bm.compress(Bitmap.CompressFormat.PNG, 100, os);
Toast.makeText(mContext, "Saving image OK", Toast.LENGTH_SHORT).show();
os.close();
}
catch (Exception e) {
Log.v("Gestures", e.getMessage());
e.printStackTrace();
}
Use this code to save a pattern in an image within an established folder.
I've been working out how to take a screenshot programmatically in android, however when it screenshots I get a toolbar and black screen captured instead of what is actually on the screen.
I've also tried to screenshot a particular TextView within the custom InfoWindow layout I created for the google map. But that creates a null pointer exception on the second line below.
TextView v1 = (TextView)findViewById(R.id.tv_code);
v1.setDrawingCacheEnabled(true);
Is there anyway to either actually screenshot what is on the screen without installing android screenshot library or to screenshot a TextView within a custom InfoWindow layout
This is my screenshot method:
/**
* Method to take a screenshot programmatically
*/
private void takeScreenshot(){
try {
//TextView I could screenshot instead of the whole screen:
//TextView v1 = (TextView)findViewById(R.id.tv_code);
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName());
Log.d("debug", "Screenshot saved to gallery");
Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT: I have changed the method to the one provided from the source
How can i take/merge screen shot of Google map v2 and layout of xml both programmatically?
However it does not screenshot anything.
public void captureMapScreen() {
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap snapshot) {
try {
View mView = getWindow().getDecorView().getRootView();
mView.setDrawingCacheEnabled(true);
Bitmap backBitmap = mView.getDrawingCache();
Bitmap bmOverlay = Bitmap.createBitmap(
backBitmap.getWidth(), backBitmap.getHeight(),
backBitmap.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(backBitmap, 0, 0, null);
canvas.drawBitmap(snapshot, new Matrix(), null);
FileOutputStream out = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ "/"
+ System.currentTimeMillis() + ".jpg");
bmOverlay.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
mMap.snapshot(callback);
}
Use this code
private void takeScreenshot() {
AsyncTask<Void, Void, Void> asyc = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
objUsefullData.showProgress("Please wait", "");
}
#Override
protected Void doInBackground(Void... params) {
try {
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmapscreen_shot = Bitmap.createBitmap(v1
.getDrawingCache());
v1.setDrawingCacheEnabled(false);
String state = Environment.getExternalStorageState();
File folder = null;
if (state.contains(Environment.MEDIA_MOUNTED)) {
folder = new File(
Environment.getExternalStorageDirectory()
+ "/piccapella");
} else {
folder = new File(
Environment.getExternalStorageDirectory()
+ "/piccapella");
}
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Create a media file name
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss", Locale.getDefault())
.format(new java.util.Date());
imageFile = new File(folder.getAbsolutePath()
+ File.separator + "IMG_" + timeStamp + ".jpg");
/*
* Toast.makeText(AddTextActivity.this,
* "saved Image path" + "" + imageFile,
* Toast.LENGTH_SHORT) .show();
*/
imageFile.createNewFile();
} else {
/*
* Toast.makeText(AddTextActivity.this,
* "Image Not saved", Toast.LENGTH_SHORT).show();
*/
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
// save image into gallery
bitmapscreen_shot.compress(CompressFormat.JPEG, 100,
ostream);
FileOutputStream fout = new FileOutputStream(imageFile);
fout.write(ostream.toByteArray());
fout.close();
Log.e("image_screen_shot", "" + imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
objUsefullData.dismissProgress();
}
};
asyc.execute();
}
Hope this will help you
I have figured it out !
/**
* Method to take a screenshot programmatically
*/
private void takeScreenshot(){
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap bitmap) {
Bitmap b = bitmap;
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss", Locale.getDefault())
.format(new java.util.Date());
String filepath = timeStamp + ".jpg";
try{
OutputStream fout = null;
fout = openFileOutput(filepath,MODE_WORLD_READABLE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
saveImage(filepath);
}
};
mMap.snapshot(callback);
}
/**
* Method to save the screenshot image
* #param filePath the file path
*/
public void saveImage(String filePath)
{
File file = this.getFileStreamPath(filePath);
if(!filePath.equals(""))
{
final ContentValues values = new ContentValues(2);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
final Uri contentUriFile = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(HuntActivity.this,"Code Saved to files!",Toast.LENGTH_LONG).show();
}
else
{
System.out.println("ERROR");
}
}
I have adapted the code from this link so it doesn't share and instead just saves the image.
Capture screen shot of GoogleMap Android API V2
Thanks for everyones help
Please try with the code below:
private void takeScreenshot(){
try {
//TextView I could screenshot instead of the whole screen:
//TextView v1 = (TextView)findViewById(R.id.tv_code);
Bitmap bitmap = null;
Bitmap bitmap1 = null;
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
try {
if (bitmap != null)
bitmap1 = Bitmap.createBitmap(bitmap, 0, 0,
v1.getWidth(), v1.getHeight());
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
v1.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName());
Log.d("debug", "Screenshot saved to gallery");
Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I faced this issue. After v1.setDrawingCacheEnabled(true); I added,
v1.buildDrawingCache();
And put some delay to call the takeScreenshot(); method.
It is fixed.