I want to save image from url to storage through picasso, but i have a problem with my code.
i've a variable to save image.
String urlImage = "http://mylink/buzz/test2.jpg";
this one is worked
but when i use
fileUrl = fileName +"." + fileType;
String urlImage = "http://mylink/buzz/" + fileUrl;
not worked
content of fileUrl is test2.jpg
here is my code to save image
private Target picassoImageTarget(Context context, final String imageDir, final String imageName) {
Log.d("picassoImageTarget", " picassoImageTarget");
ContextWrapper cw = new ContextWrapper(context);
final File directory = cw.getDir(imageDir, Context.MODE_PRIVATE); // path to /data/data/yourapp/app_imageDir
return new Target() {
#Override
public void onBitmapLoaded(final Bitmap bitmap, Picasso.LoadedFrom from) {
new Thread(new Runnable() {
#Override
public void run() {
final File myImageFile = new File(directory, imageName); // Create image file
FileOutputStream fos = null;
try {
fos = new FileOutputStream(myImageFile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Log.i("image", "image saved to >>>" + myImageFile.getAbsolutePath());
}
}).start();
}
#Override
public void onBitmapFailed(Drawable errorDrawable) {
}
#Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
if (placeHolderDrawable != null) {}
}
};
}
and its code for call picasso.
Picasso.with(DrawerActivity.this).load(url).into(picassoImageTarget(getApplicationContext(), "imageDir", fileUrl));
Related
this is my code I and I want to save this bitmap on my internal storage. The public boolean saveImageToInternalStorage is a code from google but I don't know how to use it. when I touch button2 follow the button1 action.
public class MainActivity extends Activity implements OnClickListener {
Button btn, btn1;
SurfaceView sv;
Bitmap bitmap;
Canvas canvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
btn1=(Button)findViewById(R.id.button2);
sv=(SurfaceView)findViewById(R.id.surfaceView1);
btn.setOnClickListener(this);
btn1.setOnClickListener(this);
bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
#Override
public void onClick(View v) {
canvas=sv.getHolder().lockCanvas();
if(canvas==null) return;
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
public boolean saveImageToInternalStorage(Bitmap image) {
try {
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
EDIT
From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.
public onClick(View v){
switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
}
}
private static void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-"+ o +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Modify onClick() as follows:
#Override
public void onClick(View v) {
if(v == btn) {
canvas=sv.getHolder().lockCanvas();
if(canvas!=null) {
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
} else if(v == btn1) {
saveBitmapToInternalStorage(bitmap);
}
}
There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.
I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:
if(v == btn) {
...
btn1.setEnabled(true);
}
To save file into directory
public static Uri saveImageToInternalStorage(Context mContext, Bitmap bitmap){
String mTimeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
String mImageName = "snap_"+mTimeStamp+".jpg";
ContextWrapper wrapper = new ContextWrapper(mContext);
File file = wrapper.getDir("Images",MODE_PRIVATE);
file = new File(file, "snap_"+ mImageName+".jpg");
try{
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e)
{
e.printStackTrace();
}
Uri mImageUri = Uri.parse(file.getAbsolutePath());
return mImageUri;
}
required permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You might be able to use the following for decoding, compressing and saving an image:
#Override
public void onClick(View view) {
onItemSelected1();
InputStream image_stream = null;
try {
image_stream = getContentResolver().openInputStream(myUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap image= BitmapFactory.decodeStream(image_stream );
// path to sd card
File path=Environment.getExternalStorageDirectory();
//create a file
File dir=new File(path+"/ComDec/");
dir.mkdirs();
Date date=new Date();
File file=new File(dir,date+".jpg");
OutputStream out=null;
try{
out=new FileOutputStream(file);
image.compress(format,size,out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");
image=null;
}
catch (IOException e)
{
e.printStackTrace();
}
Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
}
});
I want the application in the background to be able to take a screenshot and save the result to the clipboard. Is there an optimal solution to this problem?
You can use the following code examples
public class HelperScreenShot {
public static Bitmap takeScreenshot(View v) {
v.setDrawingCacheEnabled(true);
v.buildDrawingCache(true);
Bitmap b = Bitmap.createBitmap(v.getDrawingCache());
v.setDrawingCacheEnabled(false);
return b;
}
public static Bitmap takeScreenshotOfRootView(View v) {
return takeScreenshot(v.getRootView());
}
public static boolean takeScreenshotAndSaveIi(View v, String filename) {
return storeScreenshot(takeScreenshot(v.getRootView()), filename);
}
public static boolean storeScreenshot(Bitmap bitmap, String filename) {
if (!isExternalStorageReadable()) {
return false;
}
if (!isExternalStorageWritable()) {
return false;
}
OutputStream out;
try {
File dir = getDownloadStorageDir("ScreenShots");
File imageFile = new File(dir, filename + ".jpg");
if (!imageFile.exists()) {
imageFile.createNewFile();
}
out = new FileOutputStream(imageFile);
// choose JPEG format
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
MediaScannerConnection.scanFile(G.context, new String[]{imageFile.getAbsolutePath()}, null, null);
out.flush();
out.close();
return true;
} catch (FileNotFoundException e) {
// manage exception ...
return false;
} catch (IOException e) {
// manage exception ...
return false;
}
}
/* Checks if external storage is available for read and write */
private static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
/* Checks if external storage is available to at least read */
private static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
private static File getDownloadStorageDir(String fileName) {
// Get the directory for the user's public pictures directory.
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), fileName);
if (!Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).exists()) {
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getPath()).mkdirs();
}
if (!storageDir.exists()) {
storageDir.mkdir();
}
return storageDir;
}
}
private Single<Boolean> loadImage() {
Date date = new Date();
filename = "receipt" + date.getTime();
return Single.just(HelperScreenShot.takeScreenshotAndSaveIi(binding.v, filename));
}
private void getScreenshot() {
loadImage()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new SingleObserver<Boolean>() {
#Override
public void onSubscribe(#io.reactivex.annotations.NonNull Disposable d) {
disposables.add(d);
}
#Override
public void onSuccess(#io.reactivex.annotations.NonNull Boolean s) {
if (s) {
Snackbar snackbar = Snackbar.make(binding.v, getResources().getString(R.string.picture_save_to_galary), Snackbar.LENGTH_LONG);
snackbar.setAction(getResources().getString(R.string.navigation_drawer_open), new View.OnClickListener() {
#Override
public void onClick(View v) {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "ScreenShots/" + filename + ".jpg");
Log.d("amini", "onClick: " + file.getAbsolutePath());
Intent intent = new Intent(Intent.ACTION_VIEW).setDataAndType(
Build.VERSION.SDK_INT >= Build.VERSION_CODES.N ?
FileProvider.getUriForFile(getContext(), getContext().getPackageName() + ".provider", file) :
Uri.fromFile(file), "image/*")
.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
startActivity(intent);
}
});
snackbar.show();
} else {
Snackbar snackbar = Snackbar.make(binding.v, getResources().getString(R.string.str_frag_sync_error), Snackbar.LENGTH_LONG);
snackbar.setAction(getResources().getString(R.string.ok), v -> snackbar.dismiss());
snackbar.show();
}
}
#Override
public void onError(#io.reactivex.annotations.NonNull Throwable e) {
}
});
}
I want to add feature in my app to download a GIF Image from url to my phones storage.
How can I do this into my application
public class Download {
Context context;
String url;
ProgressDialog progressDailog;
public void saveImage(Context context, String url) {
this.context = context;
this.url = url;
progressDailog = new ProgressDialog(context);
progressDailog.setMax(100);
progressDailog.setMessage("Please wait...");
progressDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDailog.setCanceledOnTouchOutside(false);
progressDailog.show();
Glide.with(context).asBitmap()
.load(url)
.apply(new RequestOptions()
.diskCacheStrategyOf(DiskCacheStrategy.ALL)
.format(DecodeFormat.PREFER_ARGB_8888)
.override(Target.SIZE_ORIGINAL))
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
progressDailog.dismiss();
storeImage(resource);
//Log.d(TAG, "Image : " + resource);
}
});
}
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
Toast.makeText(context, "Image Downloaded", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
} catch (IOException e) {
}
}
private File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas"); /*getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas/c");*/
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs())
return null;
}
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_MERRY_CHRISTMAS.jpg");
return mediaFile;
}
}
From this code I can download the normal Image but it did not works on GIF. The GIF image downloaded and it remains static
This snippet will help you to download gif using GLIDE
Glide.with(context)
.download(url)
.listener(new RequestListener<File>() {
#Override
public boolean onLoadFailed(#Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
progressDailog.dismiss();
Toast.makeText(context, "Error saving", Toast.LENGTH_SHORT).show();
return false;
}
#Override
public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
progressDailog.dismiss();
try {
saveGifImage(context, getBytesFromFile(resource), createName(url));
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}).submit();
createName function
public String createName(String url) {
String name = url.substring( url.lastIndexOf('/')+1, url.length());
String NoExt = name.substring(0, name.lastIndexOf('.'));
if(!ext.equals(".gif")){
name = NoExt + ".jpg";
}
return name;
}
getBytesFromFile function
public byte[] getBytesFromFile(File file) throws IOException {
long length = file.length();
if (length > Integer.MAX_VALUE) {
throw new IOException("File is too large!");
}
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
InputStream is = new FileInputStream(file);
try {
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
} finally {
is.close();
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
return bytes;
}
saveGifImage function
public void saveGifImage(Context context, byte[] bytes, String imgName ) {
FileOutputStream fos = null;
try {
File externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
File customDownloadDirectory = new File(externalStoragePublicDirectory, "Merry_Christmas");
if (!customDownloadDirectory.exists()) {
boolean isFileMade = customDownloadDirectory.mkdirs();
}
if (customDownloadDirectory.exists()) {
File file = new File(customDownloadDirectory, imgName);
fos = new FileOutputStream(file);
fos.write(bytes);
fos.flush();
fos.close();
if (file != null) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, file.getName());
values.put(MediaStore.Images.Media.DISPLAY_NAME, file.getName());
values.put(MediaStore.Images.Media.DESCRIPTION, "");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/gif");
values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis());
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
ContentResolver contentResolver = context.getContentResolver();
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(context, "Image saved to " + file.getAbsolutePath(), Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
For getting GIF using Glide:
Glide.with(MainActivity.this).asFile()
.load(url)
.apply(new RequestOptions()
.format(DecodeFormat.PREFER_ARGB_8888)
.override(Target.SIZE_ORIGINAL))
.into(new Target<File>() {
#Override
public void onStart() {
}
#Override
public void onStop() {
}
#Override
public void onDestroy() {
}
#Override
public void onLoadStarted(#Nullable Drawable placeholder) {
}
#Override
public void onLoadFailed(#Nullable Drawable errorDrawable) {
}
#Override
public void onResourceReady(#NonNull File resource, #Nullable Transition<? super File> transition) {
storeImage(resource);
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
#Override
public void getSize(#NonNull SizeReadyCallback cb) {
}
#Override
public void removeCallback(#NonNull SizeReadyCallback cb) {
}
#Override
public void setRequest(#Nullable Request request) {
}
#Nullable
#Override
public Request getRequest() {
return null;
}
});
For Saving Image:
private void storeImage(File image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
return;
}
try {
FileOutputStream output = new FileOutputStream(pictureFile);
FileInputStream input = new FileInputStream(image);
FileChannel inputChannel = input.getChannel();
FileChannel outputChannel = output.getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
output.close();
input.close();
Toast.makeText(MainActivity.this, "Image Downloaded", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas"); /*getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS) + "/Christmas/c");*/
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs())
return null;
}
File mediaFile;
mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_MERRY_CHRISTMAS_"+Calendar.getInstance().getTimeInMillis() +".gif");
return mediaFile;
}
Glide can get File, worked with me:
Glide.with(context).asFile()
.load(url)
.apply(new RequestOptions()
.diskCacheStrategyOf(DiskCacheStrategy.ALL)
.format(DecodeFormat.PREFER_ARGB_8888)
.override(Target.SIZE_ORIGINAL))
.into(new SimpleTarget<File>() {
#Override
public void onResourceReady(#NonNull File resource, #Nullable Transition<? super File> transition) {
progressDailog.dismiss();
storeImage(resource);
//Log.d(TAG, "Image : " + resource);
}
});
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;
}
}
I created IGoogleServices interface on core project:
public interface IGoogleServices {
.....
public String getPlayerName();
}
Then I put the following code inside the implementaion method in MainActivity on android project:
private String name;
#Override
public String getPlayerName() {
runOnUiThread(new Runnable() {
public void run() {
name = Games.Players.getCurrentPlayer(_gameHelper.getApiClient()).getDisplayName();
}
});
return name;
}
This is simple way to tell MyGame the player name as a String:
lblPlayerName = new Label("" + googleServices.getPlayerName(), style);
stage.addActor(lblPlayerName);
BUT I can't do it in the image case.
In the same previous String case, I tried to do it in the image case:
private Uri imgUri;
#Override
public void requestImgProfile() {
runOnUiThread(new Runnable() {
public void run() {
imgUri = Games.Players.getCurrentPlayer(_gameHelper.getApiClient()).getIconImageUri();
ImageManager manager = ImageManager.create(MainActivity.this);
manager.loadImage(new ImageManager.OnImageLoadedListener() {
public void onImageLoaded(Uri arg0, Drawable drawable, boolean arg2) {
try {
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
FileOutputStream out = new FileOutputStream(imagePath);;
out = openFileOutput(imgUri + ".png", Context.MODE_MULTI_PROCESS);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}, imgUri);
};
});
}
My imgUri is:
content://com.google.android.gms.games.background/images/26s5523b/2633
What is the class type (like String) which I can tell MyGame it and libGDX libraries can treat with it?
If you have an Image URI, you can get a Bitmap via:
Uri imgUri;
Bitmap bitmap = null;
try {
InputStream inputStream = getContentResolver().openInputStream(imgUri);
bitmap = BitmapFactory.decodeStream(inputStream);
} catch (FileNotFoundException e) {
}
This works whether it is a file:// URI or content:// URI.
Then use solutions such as this answer to convert the Bitmap into something usable by libGDX.