Skip to content

Instantly share code, notes, and snippets.

@jasper07
Created July 17, 2013 04:57
Show Gist options
  • Save jasper07/6017794 to your computer and use it in GitHub Desktop.
Save jasper07/6017794 to your computer and use it in GitHub Desktop.
Android: Retrieve images from OData Media Link Entry
// cut down version
// for each customer
// retrieve image from OData Media Link Entries (Util.retrieveBitmap)
// store image on file (Util.writeBitmapToFile)
//
// later on when showing customer retrieve image from file (readBitmapFromFile - drawable)
public List<Customer> getCustomers() throws ProxyException {
List<Customer> customers = getContactsSVC().getCustomers();
// images
Bitmap image;
String imageName;
for (Customer c : customers) {
imageName = c.getCustomerID() + Constants.JPG;
image = Util.retrieveBitmap(c.getImageURI());
// TODO use content provider
File custDir = getDir(Constants.CUSTOMER, Context.MODE_WORLD_READABLE);
Util.writeBitmapToFile(image, new File(custDir,imageName));
}
package com.jasper.customer.contacts;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
public abstract class Util {
public static Bitmap retrieveBitmap(final String urlString) {
Log.d(Constants.TAG, "making HTTP trip for image:" + urlString);
Bitmap bitmap = null;
InputStream stream = null;
try {
URL url = new URL(urlString);
stream = url.openConnection().getInputStream();
bitmap = BitmapFactory.decodeStream(stream);
} catch (MalformedURLException e) {
Log.e(Constants.TAG, "Exception loading image, malformed URL",
e);
} catch (IOException e) {
Log.e(Constants.TAG, "Exception loading image, IO error", e);
} finally {
try {
if (stream != null) {
stream.close();
}
} catch (IOException e) {
Log.w(Constants.TAG, "Error closing stream", e);
}
}
return bitmap;
}
public static BitmapDrawable readBitmapFromFile(File imageFile) {
BitmapDrawable result = null;
result = new BitmapDrawable(imageFile.getAbsolutePath());
return result;
}
public static BitmapDrawable readBitmapFromInputStream(Resources resources,
InputStream inputStream) {
BitmapDrawable result = null;
result = new BitmapDrawable(resources, inputStream);
return result;
}
public static void writeBitmapToFile(Bitmap image, File location) {
try {
FileOutputStream out = new FileOutputStream(location);
image.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return customers;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment