Created
September 15, 2010 07:32
-
-
Save rummelonp/580375 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.BufferedInputStream; | |
import java.io.BufferedOutputStream; | |
import java.io.ByteArrayOutputStream; | |
import java.io.FileNotFoundException; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.InputStream; | |
import java.net.HttpURLConnection; | |
import java.net.URL; | |
import android.graphics.Bitmap; | |
import android.graphics.BitmapFactory; | |
import android.graphics.Bitmap.CompressFormat; | |
public class ImageFactory | |
{ | |
private static final CompressFormat IMAGE_FORMAT = CompressFormat.JPEG; | |
private static final int IMAGE_QUALITY = 100; | |
private static final int IO_BUFFER_SIZE = 4 * 1024; | |
public static boolean write(String urlString, String filePath) | |
{ | |
HttpURLConnection con = null; | |
InputStream input = null; | |
FileOutputStream fileOutput = null; | |
BufferedOutputStream output = null; | |
try { | |
URL url = new URL(urlString); | |
con = (HttpURLConnection) url.openConnection(); | |
con.setDoInput(true); | |
con.connect(); | |
input = new BufferedInputStream(con.getInputStream(), IO_BUFFER_SIZE); | |
ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); | |
output = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE); | |
byte[] b = new byte[IO_BUFFER_SIZE]; | |
int read; | |
while ((read = input.read(b)) != -1) { | |
output.write(b, 0, read); | |
} | |
output.flush(); | |
byte[] data = dataStream.toByteArray(); | |
Bitmap image = BitmapFactory.decodeByteArray(data, 0, data.length); | |
if (image != null) { | |
fileOutput = new FileOutputStream(filePath, false); | |
image.compress(IMAGE_FORMAT, IMAGE_QUALITY, fileOutput); | |
return true; | |
} else { | |
return false; | |
} | |
} catch (FileNotFoundException e) { | |
return false; | |
} catch (IOException e) { | |
return false; | |
} finally { | |
try { | |
if (output != null) { | |
output.close(); | |
} | |
} catch (IOException e) {} | |
try { | |
if (fileOutput != null) { | |
fileOutput.close(); | |
} | |
} catch (IOException e) {} | |
try { | |
if (input != null) { | |
input.close(); | |
} | |
} catch (IOException e) {} | |
con.disconnect(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment