android 2.1SDK - resize bitmap - android

I download and resize my bitmap using the following code :
private void downloadImage(String urlImg, ImageView v) {
Bitmap bitmap = null, resized= null;
try {
URL urlImage = new URL("http://.../" + urlImg);
HttpURLConnection connexion = (HttpURLConnection) urlImage
.openConnection();
InputStream inputStream = connexion.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);
resized = Bitmap.createScaledBitmap(bitmap, 100, 100, false);
v.setImageBitmap(resized);
connexion.disconnect();
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
and in my onCreate() function, I create dynamically ImageViews where i use my previous function
ImageView view = new ImageView(this);
downloadImage(list.getOneAnnonce(i).getPhoto(), view);
trMain.addView(view);
if I dont try to resize bitmap, there is no error but if i try to resize -> Force close

Related

How to disable image from saving into internal memory while downloading from an url

I am using the following code to download an image from an url, then saving to sqlite and then view in imageview in an activity.
new LoadProfileImage().execute(jsonObject.getString("image"), id, title, promoexpdate, String.valueOf(i),flag,promostartDate);
The above code is used to call the function to do the above work.
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
String x,y,z,a,w,s;
protected Bitmap doInBackground(String... uri) {
String url = uri[0];
Log.d("ImageURL",url);
x = uri[1];
y = uri[2];
z = uri[3];
a = uri[4];
w = uri[5];
s = uri[6];
Log.d("LogValue",url+x+y+z+a+w+s);
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(url).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (IOException e) {
Log.e("ErroronImageParsing", e.getLocalizedMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
if (result != null) {
int width = result.getWidth();
int height = result.getHeight();
Bitmap newBitmap = Bitmap.createScaledBitmap(result, width / 2, height / 2, true);
ByteArrayOutputStream out = new ByteArrayOutputStream();
newBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
buffer = out.toByteArray();
if (result!= newBitmap){
result.recycle();
}
Log.d("ImageUploaded", "Success");
}
try {
dbManager.open();
Cursor cursor = dbManager.fetch_PromsID(x);
if (cursor.getCount() > 0){
String fla = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PRO_FLAG));
String pri_ID = cursor.getString(cursor.getColumnIndex(DatabaseHelper.PRO_ID));
if (!w.equals(fla)) {
dbManager.update_Promotions(pri_ID,y,z, buffer,w,s);
}
}else {
dbManager.insertPromotions(x,y,z,buffer,w,s);
}
} catch (SQLException e) {
e.printStackTrace();
}
SqliteData();
panel.setVisibility(View.GONE);
dbManager.close();
}
}
Here, when the code below is executed, image from the url is saved into internal storage. I wish to disable the auto saving while maintaining my intention. Thanks in advance...
Bitmap newBitmap = Bitmap.createScaledBitmap(result, width / 2, height / 2, true);
ByteArrayOutputStream out = new ByteArrayOutputStream();
newBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
buffer = out.toByteArray();
Try to use third library like Picasso or Glid
that offer
loading without caching
loading with memory or storage caching
you can do it with single line of code
Picasso.with(context).load(imageUrl)
.error(R.drawable.error)
.placeholder(R.drawable.placeholder)
.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.into(imageView);

How to get String type in setImageResource method?

My code: holder.icon.setImageResource(current.imageUrl); here the imageUrl is been declared in String. But setImageResource takes only int. Can anyone provide me a solution how to get a string or is there anyother method available for it?
I think u are fetch the image from internet.
private Bitmap getBitMapFromUrl( String imageuri){
HttpURLConnection connection=null;
try {
URL url=new URL(imageuri);
connection= (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream is=connection.getInputStream();
Bitmap mybitmap=BitmapFactory.decodeStream(is);
return mybitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}}
pass the string value and return the bitmap.
holder.icon.setImageBitmap(getBitmapFromUrl());
you are using the "setImageResource" !
it expects a Resource (usually a drawable resource), hence the int requirement.
the download solution suggested by #Mayuri Joshi might fit your needs, if not, please provide more information regarding what it is you are trying to accomplish :)
You have to download the image firstly
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
Then use the Imageview.setImageBitmap to set bitmap into the ImageView

Set button background image from url

I was wondering how i set a buttons background image from a URL on android.
The buttons id is blue if you need to know that.
I tried this but it didn't work.
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
I used the next code for obtain the bitmap, one important thing is sometimes you can't obtain the InputStream, and that is null, I make 3 attemps if that happens.
public Bitmap generateBitmap(String url){
bitmap_picture = null;
int intentos = 0;
boolean exception = true;
while((exception) && (intentos < 3)){
try {
URL imageURL = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageURL.openConnection();
conn.connect();
InputStream bitIs = conn.getInputStream();
if(bitIs != null){
bitmap_picture = BitmapFactory.decodeStream(bitIs);
exception = false;
}else{
Log.e("InputStream", "Viene null");
}
} catch (MalformedURLException e) {
e.printStackTrace();
exception = true;
} catch (IOException e) {
e.printStackTrace();
exception = true;
}
intentos++;
}
return bitmap_picture;
}
Don't load the image directly in the UI (main) thread, for it will make the UI freeze while the image is being loaded. Do it in a separate thread instead, for example using an AsyncTask. The AsyncTask will let the image load in its doInBackground() method and then it can be set as the button background image in the onPostExecute() method. See this answer: https://stackoverflow.com/a/10868126/2241463
Try this code:
Bitmap bmpbtn = loadBitmap(yoururl);
button1.setImageBitmap(bmpbtn);

How to resize image for list view

i am loading image and title for list view from webservices text is f9 but image is too big.how to resize it and i want to set text in right side and image in left side in each row of list view .i am using this method Bitmap resized = Bitmap.createScaledBitmap(bitmap, 70, 70, true); but nothing appearing on emulator This is my costant class where i am loading image
public static Bitmap loadPhotoBitmap(URL url) {
Bitmap bitmap = null ;
InputStream in = null;
BufferedOutputStream out = null;
BufferedOutputStream bfs = null;
try {
FileOutputStream fos = new FileOutputStream("/sdcard/photo-tmp.jpg");
bfs = new BufferedOutputStream(fos);
in = new BufferedInputStream(url.openStream(),8192);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 8192);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bfs.write(data, 0, data.length);
bfs.flush();
BitmapFactory.Options opt = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opt);
//System.out.println(resized);
Bitmap resized = Bitmap.createScaledBitmap(bitmap, 70,70, true);
return resized;
} catch (IOException e) {
// android.util.Log.e("message", "Could not load photo: " + this, e);
System.out.println("Exception while loading image");
} finally {
closeStream(in);
closeStream(out);
closeStream(bfs);
}
System.out.println("returning");
return bitmap;
}
LazyAdapter.class
public View getView(int position, View convertView, ViewGroup parent) {
System.out.println("Exception before..");
String strUrl = Constants.vctrImagePath.elementAt(counter).toString();// getting imgurl
System.out.println("Urls...." + strUrl);
URL url =null;
try {
url = new URL(strUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap bitmap = Constants.loadPhotoBitmap(url);
//Bitmap resized = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
RelativeLayout layout = new RelativeLayout(mContext);
RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT);
TextView text1 = new TextView(mContext);
text1.setText(Constants.vctrCategory.elementAt(counter).toString());
LayoutParams params1 = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
params1.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
text1.setLayoutParams(params1);
text1.setTextSize(20);
text1.setGravity(Gravity.RIGHT);
layout.addView(text1);
ImageView img = new ImageView(mContext);
img.setImageBitmap(bitmap);
layout.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
layout.addView(img);
counter++;
return layout;
}
private void setContentView(ImageView image) {
// TODO Auto-generated method stub
}
Instead of
BitmapFactory.Options opt = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opt);
Replace that with
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, opts);
problem was not in my this bitmapfactory class.i hav resolved my isssue.
i just change code in my lazy adapter class.
Bitmap bitmap = Constants.DownloadImage(strUrl);
Bitmap resized=null;
if(bitmap!=null){
resized = Bitmap.createScaledBitmap(bitmap, 100, 100, true);
}else{
System.out.println(strUrl+ "no image here");
}
before i was resizing image in my list view.while it will resize in adpter class of list view.

Problem with downloading image from URL

I use such code for downloading image from URL:
public static Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
When I send URL "http://java.sogeti.nl/JavaBlog/wp-content/uploads/2009/04/android_icon_256.png" it works fine, but when I use "http://www.hospimedica.com/images/stories/articles/article_images/_CC/20110328%20-%20DJB146.gif" it returns me null.
What's wrong with this URL?
Why are you writing your own method to downlaod an image ? Android has inbuilt method to achieve this.. Just use
URL url = new URL("Your url");
Bitmap bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());

Categories

Resources