How to save Gif files from url into my phone? - java

I'm a beginner Android Developer (graduating univ and looking for a job)
So, I'm developing app uploading so many GIF files and others downloading and save their phones.
I can download GIF or other image files and save to my directory. But the problem is that Bitmap.compress not support GIF(only png,jpg..etc).
So, I compressed GIF files to png or jpg. As expected, the image didn't animated. My images are all GIF files. How can I compress GIF files and save to my directory??
Bellow is my code
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final ViewGroup view1 = (ViewGroup) inflater.inflate(R.layout.fragment1, container, false);
Button button = (Button) view1.findViewById(R.id.saveBtn);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
new Thread(new Runnable() {
#Override
public void run() {
try{
bm = getBitmap(myUrl);
}catch (Exception e){
}finally {
if(bm != null){
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
getAlbumStorageDir(albumName,"GifImage_"+num);
num++;
}//end run()
});
}
}
}
}).start();
return view1;
}
private Bitmap getBitmap(String url) {
URL imgUrl = null;
HttpURLConnection connection = null;
InputStream is = null;
Bitmap retBitmap = null;
try{
imgUrl = new URL(url);
connection = (HttpURLConnection) imgUrl.openConnection();
connection.setDoInput(true);
connection.connect();
is = connection.getInputStream(); // get inputstream
retBitmap = BitmapFactory.decodeStream(is);
}catch(Exception e) {
e.printStackTrace();
return null;
}finally {
if(connection!=null) {
connection.disconnect();
}
return retBitmap;
}
}
public void getAlbumStorageDir(String albumName, String imageName) {
String root = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
String folder_name = "/" + albumName + "/";
String file_name = imageName;
String string_path = root + folder_name;
String save_path = string_path + file_name;
File file_path;
try {
file_path = new File(string_path);
if (!file_path.isDirectory()) {
file_path.mkdirs();
}
FileOutputStream out = new FileOutputStream(string_path + file_name);
bm.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://"+save_path))); //갤러리 갱신
Toast.makeText(getContext(), "save success ", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

CursorAdapter with images are loading weird

I have a simple CursorAdapter that gets a title and image.
It shows the title and then loads the image from the Internet.
However, when I call the image loader the image is loaded at the wrong place, and it starts going really wild: see here.
My complete code is here.
The adapter is RestaurantListActivityCursorAdapter
public class RestaurantListActivityCursorAdapter extends CursorAdapter {
/* Api variables */
String websiteURL = "http://cicolife.com";
public RestaurantListActivityCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.activity_main_list_item, parent, false);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
// Extract properties from cursor
int get_Id = cursor.getInt(cursor.getColumnIndexOrThrow("_id"));
String getTitle = cursor.getString(cursor.getColumnIndexOrThrow("title"));
String getImage = cursor.getString(cursor.getColumnIndexOrThrow("image"));
// Name
TextView listViewTitle = (TextView) view.findViewById(R.id.listViewTitle);
listViewTitle.setText(getTitle);
// Img
ImageView listViewImage = (ImageView) view.findViewById(R.id.listViewImage);
if(getImage != null) {
if (!(getImage.equals(""))) {
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+ File.separatorChar+"/Android/data/com.nettport.restaurants/imgs";
File file = new File (destinationPath, getImage);
if (file.exists ()){
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
listViewImage.setImageBitmap(myBitmap);
}
else {
String loadImage = websiteURL + "/_cache/" + getImage;
new HttpRequestImageLoadTask(context, loadImage, listViewImage, getImage,"imgs").execute();
}
}
}
}
}
The image loader HttpRequestImageLoadTask
public class HttpRequestImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private String url;
private ImageView imageView;
private LinearLayout linearLayout;
private Resources resources;
private Context context;
private String storeDirectory;
private String imageName;
public interface TaskListener {
void onFinished(String result);
}
public HttpRequestImageLoadTask(Context ctx, String url, ImageView imageView, String imgName, String storeDirectory) {
this.context = ctx;
this.url = url;
this.imageView = imageView;
this.imageName = imgName;
this.storeDirectory = storeDirectory;
}
public HttpRequestImageLoadTask(Context ctx, String url, LinearLayout linearLayout, Resources resources, String imgName, String storeDirectory) {
this.context = ctx;
this.url = url;
this.linearLayout = linearLayout;
this.imageName = imgName;
this.storeDirectory = storeDirectory;
}
#Override
protected Bitmap doInBackground(Void... params) {
if (checkIfCacheExists(imageName)) {
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
File file = new File (destinationPath, imageName);
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
return myBitmap;
} else {
try {
URL urlConnection = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
saveImage(myBitmap);
return myBitmap;
} catch(Exception e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if(imageView != null) {
imageView.setImageBitmap(result);
} else {
if(linearLayout != null){
BitmapDrawable background = new BitmapDrawable(resources, result);
linearLayout.setBackground(background);
}
}
}
public boolean checkIfCacheExists(String imgName){
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
File file = new File (destinationPath, imgName);
return file.exists();
}
private void saveImage(Bitmap finalBitmap) {
// Make dir
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
File folder = new File(destinationPath);
try {
if (!folder.exists()) {
// Make Android
destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android";
folder = new File(destinationPath);
if (!folder.exists()) {
folder.mkdir();
}
// Make Android/data
destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data";
folder = new File(destinationPath);
if (!folder.exists()) {
folder.mkdir();
}
// Make Android/data/com.nettport.restaurants
destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants";
folder = new File(destinationPath);
if (!folder.exists()) {
folder.mkdir();
}
// Make Android/data/com.nettport.restaurants/storeDirectory
destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+File.separatorChar+"/Android/data/com.nettport.restaurants/" + storeDirectory;
folder = new File(destinationPath);
if (!folder.exists()) {
folder.mkdir();
}
}
} catch (Exception e){
Toast.makeText(context, "Could not create directory:\n" + e.toString(), Toast.LENGTH_LONG).show();
}
if(imageName != null) {
File file = new File(destinationPath, imageName);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
// Toast.makeText(context, "Cant save image\n" + e.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
You have not put any else condition for your ImageView in your adapter. I see there are several else blocks are missing here.
if(getImage != null) {
if (!(getImage.equals(""))) {
String destinationPath = android.os.Environment.getExternalStorageDirectory().getPath()+ File.separatorChar+"/Android/data/com.nettport.restaurants/imgs";
File file = new File (destinationPath, getImage);
if (file.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
listViewImage.setImageBitmap(myBitmap);
} else {
String loadImage = websiteURL + "/_cache/" + getImage;
// Add nothing here when the image is being fetched
listViewImage.setImageBitmap(null);
new HttpRequestImageLoadTask(context, loadImage, listViewImage, getImage,"imgs").execute();
}
} else {
// Add an else block here when image is equals ""
listViewImage.setImageBitmap(null);
}
} else {
// Add an else block here when image is null
listViewImage.setImageBitmap(null);
}
You need to specify every possible combination in your adapter while loading the images in your ImageView.
And if you have the image url from server, just use Glide to load the images when they are not available in cache.

Gallery doesn't refresh using MediaScan

I have the following Java code which downloads an image from an URL.
I can see the image downloaded in the folder, but the image does not appear in gallery. Only if I restart phone, Samsung S7 with android 7, I can see images in gallery. What can I do to have the images in gallery in real time after I downloaded them?
public class DetailsImgActivity extends AppCompatActivity {
private static final String TAG = "DetailsImgActivity";
private ImageView imageViewPoze;
private Button buttonDownload;
private static final int PERMISSION_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_img);
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, PERMISSION_REQUEST_CODE);
}
// image url stored in imageID
final String imageId = getIntent().getStringExtra("ImageId");
imageViewPoze = findViewById(R.id.imageViewPozeC);
Picasso.get().load(imageId).into(imageViewPoze);
buttonDownload = findViewById(R.id.btn_Download_Img);
buttonDownload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
downloadFile(imageId);
}
});
}
private void downloadFile(String url) {
Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://firebasestorage.blabla.com/");
Retrofit retrofit = builder.build();
FileDownloadClient fileDownloadClient = retrofit.create(FileDownloadClient.class);
Call<ResponseBody> call = fileDownloadClient.downloadFile(url);
call.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, final Response<ResponseBody> response) {
// if (response.isSuccess()) {
Log.d(TAG, "server contacted and has file");
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... voids) {
boolean writtenToDisk = writeResponseBodyToDisk(response.body());
return null;
}
}.execute();
//after the image has been downloaded -refresh gallery
**Toast.makeText(getApplicationContext(), "File downloaded with success!", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}**
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "error");
}
});
}
private boolean writeResponseBodyToDisk(ResponseBody body) {
try {
String folder_main = Constants.dirName;
File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM), folder_main);
if (!f.exists()) {
f.mkdirs();
}
// todo change the file location/name according to your needs
File futureStudioIconFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM+"/"+ Constants.dirName)
+ File.separator + UUID.randomUUID()+".jpg");
InputStream inputStream = null;
OutputStream outputStream = null;
try {
byte[] fileReader = new byte[4096];
long fileSize = body.contentLength();
long fileSizeDownloaded = 0;
inputStream = body.byteStream();
outputStream = new FileOutputStream(futureStudioIconFile);
while (true) {
int read = inputStream.read(fileReader);
if (read == -1) {
break;
}
outputStream.write(fileReader, 0, read);
fileSizeDownloaded += read;
Log.d(TAG, "file download: " + fileSizeDownloaded + " of " + fileSize);
}
outputStream.flush();
return true;
} catch (IOException e) {
return false;
} finally {
if (inputStream != null) {
inputStream.close();
}
if (outputStream != null) {
outputStream.close();
}
}
} catch (IOException e) {
return false;
}
}
}
I used the follwing code, but If I don't reboot phone, I can't see the picture in gallery.
**Toast.makeText(getApplicationContext(), "File downloaded with success!", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
else
{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}**

Download a image from server to android and show in imageview

I have an server (i use GlassFish). I am able to send Json or XML etc. with http to my android device. I saw an example to upload a picture from my android device to the server. That converts my picked image to byte, converts to String and back at my server. So i can put it on my PC (server).
Now i just want the opposite: get a picture from my PC and with the URL get the image (bitmap here) to imageview. but with debugging bmp seems to be "null". google says its because my image is not a valid bitmap (so maybe something is wrong at my server encoding?).
What does i need to change to this code to get it working?
Server code:
public class getImage{
String imageDataString = null;
#GET
#Path("imageid/{id}")
public String findImageById(#PathParam("id") Integer id) {
//todo: schrijf een query voor het juiste pad te krijgen!
System.out.println("in findImageById");
File file = new File("C:\\Users\\vulst\\Desktop\\MatchIDImages\\Results\\R\\Tensile_Hole_2177N.tif_r.bmp");
try{
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
imageDataString = Base64.encodeBase64URLSafeString(imageData);
imageInFile.close();
System.out.println("Image Successfully Manipulated!");
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
return imageDataString;
}
}
and this is the android side (android studio):
public class XMLTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
java.net.URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String line) {
super.onPostExecute(line);
byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);
try {
Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
ivFoto.setImageBitmap(bmp);
}catch (Exception e){
Log.d("tag" , e.toString());
}
}
}
Have you tried HttpURlConnection?
Here's a sample code:
private class SendHttpRequestTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... params) {
try {
URL url = new URL("http://xxx.xxx.xxx/image.jpg");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}catch (Exception e){
Log.d(TAG,e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
ImageView imageView = (ImageView) findViewById(ID OF YOUR IMAGE VIEW);
imageView.setImageBitmap(result);
}
}
I hope i could help
You can use Glide it is simplest way to load image
This is how you can save image
Glide.with(context)
.load(image)
.asBitmap()
.into(new SimpleTarget<Bitmap>() {
#Override
public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
String name = new Date().toString() + ".jpg";
imageName = imageName + name.replaceAll("\\s+", "");
Log.d(TAG, "onResourceReady: imageName = " + imageName);
ContextWrapper contextWrapper = new ContextWrapper(mContext);
File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);
File myPath = new File(directory, imageName);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(myPath);
resource.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
and this is how you can read the image
ContextWrapper contextWrapper = new ContextWrapper(mContext);
File directory = contextWrapper.getDir("imageDir", Context.MODE_PRIVATE);
String path = directory.getAbsolutePath();
path = path + "/" + imageName;
Glide.with(mContext).load(path).into(your imageview);
Why don't you use Glide?
For build.gradle in your app module:
dependencies {
compile 'com.github.bumptech.glide:glide:3.7.0'
...
}
Then:
Glide
.with(context) // replace with 'this' if it's in activity
.load("http://www.google.com/.../image.gif")
.into(R.id.imageView);
Try using Base64.encodeBase64String(imageData) with out using the URLSafeString.
If there are people who are also trying to do it my way, this is working:
public class XMLTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
java.net.URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String line) {
super.onPostExecute(line);
byte[] imageByteArray = Base64.decode(line , Base64.DEFAULT);
try {
Bitmap bmp = BitmapFactory.decodeByteArray(imageByteArray, 0, imageByteArray.length);
ivFoto.setImageBitmap(bmp);
}catch (Exception e){
Log.d("tag" , e.toString());
}
}
}
#Stateless
#Path("getImage")
public class getImage {
//todo: capture error inandroid + take just path!
String imageDataString = null;
#GET
#Path("imageid/{id}")
public String findImageById(#PathParam("id") Integer id) {
//todo: schrijf een query voor het juiste pad te krijgen!
System.out.println("in findImageById");
File file = new File("C:\\Users\\vulst\\Desktop\\MatchIDImages\\Results\\R\\Tensile_Hole_2177N.tif_r.bmp");
try{
// Reading a Image file from file system
FileInputStream imageInFile = new FileInputStream(file);
byte imageData[] = new byte[(int) file.length()];
imageInFile.read(imageData);
// Converting Image byte array into Base64 String
imageDataString = Base64.encodeBase64String(imageData);
imageInFile.close();
System.out.println("Image Successfully Manipulated!");
} catch (FileNotFoundException e) {
System.out.println("Image not found" + e);
} catch (IOException ioe) {
System.out.println("Exception while reading the Image " + ioe);
}
return imageDataString;
}
}
I hope this code is useful.
go to your MainActivity.java and try this code:
public class MainActivity extends AppCompatActivity {
ImageView imageView;
public void downloadImage(View view)
{
Log.i("Button","Tapped");
DownloadImage task = new DownloadImage();
Bitmap result = null;
try {
result = task.execute("https://vignette.wikia.nocookie.net/disney/images/0/0a/ElsaPose.png/revision/latest?cb=20170221004839").get();
}
catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
imageView.setImageBitmap(result);
}
public class DownloadImage extends AsyncTask<String, Void, Bitmap>
{
#Override
protected Bitmap doInBackground(String... imageurls) {
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(imageurls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
InputStream in =httpURLConnection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(in);
return myBitmap;
}
catch (MalformedURLException e) {
e.printStackTrace();
return null;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView)findViewById(R.id.imageView);
}
}
Don't forget to add this piece of code in your AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>

Universal Image Loader - Save Image to SD-Card

I'm using the universal image loader for my app. I want to save the current image displayed by the ViewPager to the SD-Card however the code I have below is saving the wrong image to the SD-Card. It saves the images at random only. I need to way of knowing how to retrieve the current bitmap of the image and saving it. I don't know any other alternatives of getting the bitmap of the current image and saving it to the SD-Card. The way I'm getting the bitmap currently is through "Bitmap bitmap = loadedImage". Your help would be greatly appreciated. Cheeers.
public class ImagePagerFragment extends BaseFragment implements View.OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fr_image_pager, container, false);
ViewPager pager = (ViewPager) rootView.findViewById(R.id.pager);
pager.setAdapter(new ImageAdapter());
pager.setCurrentItem(getArguments().getInt(Constants.Extra.IMAGE_POSITION, 0));
return rootView;
}
private class ImageAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup view, int position) {
final View imageLayout = inflater.inflate(R.layout.item_pager_image, view, false);
assert imageLayout != null;
final christ.triumphant.TouchImageView imageView = (christ.triumphant.TouchImageView) imageLayout.findViewById(R.id.imagei);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
ImageLoader.getInstance().displayImage(imageUrls[position], imageView, options, new SimpleImageLoadingListener() {
..
#Override
public void onLoadingComplete(String imageUri, View view, final Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
isave = (Button) getView().findViewById(R.id.save);
isave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Bitmap bitmap = loadedImage;
File folder = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/HD GOSPEL LOCKSCREENS");
File f = new File(folder, String.valueOf(System.currentTimeMillis()) + "HDGL.PNG");
try {
FileOutputStream out = new FileOutputStream(f);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Toast.makeText(getActivity(), "Image Successfully Saved", Toast.LENGTH_LONG).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT)
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File ff = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(ff);
mediaScanIntent.setData(contentUri);
getActivity().sendBroadcast(mediaScanIntent);
}
else
{
getActivity().sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
ishare = (Button) getView().findViewById(R.id.share);
ishare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
Bitmap icon = loadedImage;
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
icon.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "temporary_file.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/temporary_file.jpg"));
startActivity(Intent.createChooser(share, "Share Image"));
Toast.makeText(getActivity(), "Image Successfully Shared", Toast.LENGTH_LONG).show();
}
});
}
});
view.addView(imageLayout, 0);
return imageLayout;
}
... ... ... }

Capture picture from webview loading local html

I'm trying to capture a image from the webiview, it works when I try to loadUrl from the web, but when I try to load a local html file in assets or html in a String it crashs with the following error:
java.lang.IllegalArgumentException: width and height must be > 0
at android.graphics.Bitmap.createBitmap(Bitmap.java:638)
at android.graphics.Bitmap.createBitmap(Bitmap.java:620)
My Code is:
//Create the webview
WebView w = new WebView(this);
w.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
//get the picture from webview
Picture picture = view.capturePicture();
Bitmap b = Bitmap.createBitmap(picture.getWidth(),
picture.getHeight(), Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(b);
picture.draw(c);
FileOutputStream fos = null;
try {
String path = Environment.getExternalStorageDirectory().toString();
File dir = new File(path, "/Movel/media/img/");
if (!dir.isDirectory()) {
dir.mkdirs();
}
String arquivo = "darf_"+ System.currentTimeMillis() + ".jpg";
File file = new File(dir, arquivo);
fos = new FileOutputStream(file);
String imagePath = file.getAbsolutePath();
//scan the image so show up in album
MediaScannerConnection.scanFile(MainActivity.this, new String[] { imagePath },
null, new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
}
});
if (fos != null) {
b.compress(Bitmap.CompressFormat.JPEG, 90, fos);
fos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
setContentView(w);
String html = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=ISO-8859-1'> " +
"<title>Demo Html</title> </head> <body> <H1>Testing One Two Three</H1> </body></html>";
//load from assets
//w.loadDataWithBaseURL("file:///android_asset/", Strings.converterParaElementosHTMLEspeciais(html), "text/html", "iso-8859-1", null);
//w.loadUrl("file:///android_asset/darf.html");
//w.loadUrl("https://www.google.com.br");
w.loadData(html, "text/html", "iso-8859-1");
this error because your WebView width and height is 0, so you must Layout your WebView first, then try this code:
myWebView.setWebChromeClient(new WebChromeClient() {
#Override
public void onProgressChanged(WebView view, int newProgress) {
super.onProgressChanged(view, newProgress);
if (newProgress == 100) {
view.post(new Runnable() {
#Override
public void run() {
// take the snapshot here
}
});
}
}
});

Categories