I want to convert bitmap to URI conversion I am using google image search API from this API I got image URL from this URL I converted it to a bitmap then I want to convert from this bitmap to URI using this sample but I get a null value.
private class GetXMLTask extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... urls) {
Bitmap map = null;
for (String url : urls) {
map = downloadImage(url);
}
return map;
}
// Sets the Bitmap returned by doInBackground
#Override
protected void onPostExecute(Bitmap result) {
imagQest.setImageBitmap(result);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(ctx.getContentResolver(),
result, "Title", null);
LivLog.info(this.getClass(), "bit map conversion is" + result
+ path);
}
// Creates Bitmap from InputStream and returns it
private Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
// stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
private InputStream getHttpConnection(String urlString)
throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
} catch (Exception ex) {
ex.printStackTrace();
}
return stream;
}
}
How to resolve this?
Here is how you'd convert Bitmap to Uri:
private Uri getImageUri(Context context, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(context.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
Pass Bitmap while calling this method:
getImageUri(this,bitmap);
try below code:-
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
for more info see below link:-
http://colinyeoh.wordpress.com/2012/05/18/android-getting-image-uri-from-bitmap/
Related
As seen in this issue there are two methods in Box android-content-sdk that return a request:
How to get thumbnails with box android-content-sdk (notV2)
The target of the first is a local file and the other a OutputStram object.
In my case I would get a bitmap in a AsyncTask like this:
Bitmap bm = BitmapFactory.decodeStream(InputStream is)
So finding no solution with the Box android-sdk-content, I tried to convert the outputStream to InputStream like this:(This method is called in AsynckTask)
protected Bitmap getThumbBox(final String id, final BoxApiFile apiFile) throws IOException {
Bitmap bitmap = null;
PipedInputStream in = new PipedInputStream();
final PipedOutputStream out = new PipedOutputStream(in);
new Thread(
new Runnable(){
public void run(){
//put your code that writes data to the outputstream here.
BoxRequestsFile.DownloadThumbnail downloadThumbnail = apiFile.getDownloadThumbnailRequest(out,id);
}
}
).start();
//data can be read from the pipedInputStream here.
bitmap = BitmapFactory.decodeStream(in);
return bitmap;
}
According with this:
http://io-tools.sourceforge.net/easystream/outputstream_to_inputstream/Pipes.html
But with no success.
Any ideas?
Thanks.
Here is how I managed to get the thumbnail into a bitmap:
protected Bitmap getThumbBox(final String id, final BoxSession session) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
BoxDownload req = null;
try {
req = new BoxApiFile(session).getDownloadThumbnailRequest(bos, id).setMinSize(256).send();
} catch (BoxException e) {
e.printStackTrace();
}
byte[] byteArr = bos.toByteArray();
Bitmap bm = BitmapFactory.decodeByteArray(byteArr, 0, byteArr.length);
return bm;
}
I have the code for downloading image from URL to SDCard, but my device can set up the image ONLY from bitmap.
The question is how I can consume image from URL directly into SQLite Database and then retreive it as the bitmap?
Thanks for any help
public void getNewLogoFromURL(String logo) throws IOException {
new GetLogo().execute(logo);
}
class GetLogoForReceipt extends AsyncTask <String, Void, Void> {
#Override
protected Void doInBackground(String... params) {
try {
downloadFile(params[0]);
} catch ( IOException e ) {
}
return null;
}
}
public void downloadFile(String url) throws IOException {
DataOutputStream fos = null;
try {
File dest_file = new File("/sdcard/Pictures/applicationLogo.png");
URL u = new URL(url);
URLConnection conn = u.openConnection();
int contentLength = conn.getContentLength();
DataInputStream stream = new DataInputStream(u.openStream());
byte[] buffer = new byte[contentLength];
stream.readFully(buffer);
stream.close();
fos = new DataOutputStream(new FileOutputStream(dest_file));
fos.write(buffer);
fos.flush();
} finally {
fos.close();
}
}
//Device image settingUp code
String[] fileList = { "applicationLogo.png" };
Bitmap[] bitmap = new Bitmap[fileList.length];
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap2 = BitmapFactory.decodeFile("/sdcard/Pictures/applicationLogo.png", options);
for ( int i = 0; i < fileList.length; i++ ) {
bitmap[i] = bitmap2;
}
int ret;
printer = new LinePrinter();
ret = printer.open(device);
ret = printer.setBitmap(bitmap);
Storing bitmaps/images in sqlite database is a bad idea. Download the image to the sd card and save the location in the data base and retrieve the image from sd card when you required.
The below code shows getting bitmap from sdcard.
public Bitmap createBitMap(String path){
File file = new File(path);
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
return bitmap;
}
I return a Bitmap object according to a url, and the code for download picture:
URL url = new URL(imageUrlStr);
URLConnection conn = url.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream in = conn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(in);
in.close
Then I save it to sdcard. It is ok to save picture.
Now the problem is it download the picture A when use this url to access. But it now shows another B picture in SDCARD. How to solve this problem?
You can identify images by hash-code. Not a perfect solution, good for the demo
private Bitmap getBitmap(String url) {
String filename = String.valueOf(url.hashCode());
File f = new File(cacheDir, filename);
// from SD cache
Bitmap b = decodeFile(f);
if (b != null)
return b;
// from web
try {
Bitmap bitmap = null;
InputStream is = new URL(url).openStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
private void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
/** decodes image and scales it to reduce memory consumption*/
private Bitmap decodeFile(File f) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
return BitmapFactory.decodeStream(new FileInputStream(f));
} catch (FileNotFoundException e) {
}
return null;
}
Use you just need to use method "getBitmap(String)" with your desired url as String
I am working on API. We have provided Url of Images. I have to show image from that Url in my list Activity for which custom Adapter is used. How can I set image throw url? I have spent almost two days in it. I used image view in my Activity.
try below code in your activity, you will get Bitmap object, using setImageBitmap(Bitmap bmt) you can do.
Method:
public Bitmap getBitmap(String url) {
Log.d("getBitmap", "getBitmap");
Bitmap bm = null;
try {
URL aURL = new URL(url);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(new FlushedInputStream(is));
bis.close();
is.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return bm;
}
inner class:
class FlushedInputStream extends FilterInputStream {
public FlushedInputStream(InputStream inputStream) {
super(inputStream);
}
}
see this complete example
Use this code to get bitmap image from file ,
Bitmap bitmapImage = BitmapFactory.decodeFile(//File path);
imageView.setImageBitmap(bitmapImage);
and you can get file from uri through the below method ,
private File getFileFromUri(Uri uri) throws IOException {
Cursor cursor = managedQuery(uri, null, null, null, null);
if (cursor.getCount() == 0) {
throw new IOException(String.format("cannot find data from %s",
uri.toString()));
} else {
cursor.moveToFirst();
}
String filePath = cursor.getString(cursor
.getColumnIndex(Video.VideoColumns.DATA));
File file = new File(filePath);
cursor.close();
return file;
}
Hope this will be helpful to you
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());