How do I get a bitmap image from InputStream(base64 String) in Android?
Below is my code:
protected Bitmap doInBackground(Void... params) {
Bitmap image;
URL url1 = null;
try {
url1 = new URL("http://sunnyfacemash.atwebpages.com/get.php"); // url
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
image = BitmapFactory.decodeStream(url1.openConnection().getInputStream());
return image;
} catch (IOException e) {
image = null;
e.printStackTrace();
}
return image;
}
Download stream to string, then use Base64.decode on it and feed this to BitmapFactory.
Use ByteArrayInputStream for factory
Related
I would like to download an image from an url, using this example:
public Bitmap getBitmapFromURL(String src) {
try {
java.net.URL url = new java.net.URL(src);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
Unfortunately the returned myBitmap is null, and I have no idea why. The url is a local ip: http://192.168.0.101:7777/my_image.png
I get no error messages
If I open this link in the browser, it displays it.
android:usesCleartextTraffic="true" is enabled, and my json requests work with Volley.
I tried to use BufferedInputStream, but that also does not work
If the bitmap would become to big for available memory BimapFactory.decodeStream() returns null.
So you are trying to load a picture with a big resolution.
Try to load a small picture and it will go.
How simple and cool is this? when you are using Glide
ImageView imageView = findViewById(R.id.imageView);
Glide.with(this)
.asBitmap()
.load("https://www.google.com/images/srpr/logo11w.png")
.into(new CustomTarget<Bitmap>() {
#Override
public void onResourceReady(#NonNull Bitmap resource, #Nullable Transition<? super Bitmap> transition) {
imageView.setImageBitmap(resource);
}
#Override
public void onLoadCleared(#Nullable Drawable placeholder) {
}
});
Or you can try these option as well
public static Bitmap loadImage(String imageUrl) {
Bitmap bitmap = null;
try {
URL url = new URL(imageUrl);
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
or
public static Bitmap downloadImage(String urlImage) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
URL url = new URL(urlImage);
stream = getHttpConnection(url);
bitmap = BitmapFactory.
decodeStream(new FlushedInputStream(stream), null, bmOptions);
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
return bitmap;
}
I am trying to download the image from url and save it in a file. But it's not getting saved. So as I debug the code I found that bitmap is always null.
code:
public class ImageUserTask extends AsyncTask<Void, Void,String> {
String strURL, imageprofile;
Bitmap mBitmap = null;
Context mContext;
private File profileFile;
public ImageUserTask(Context context, String url) {
this.strURL = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected String doInBackground(Void... params) {
Bitmap bitmap = null;
File directory = null;
try {
URL url = new URL(strURL);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
// InputStream input = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream()); //This bitmap is null always
directory = Environment.getExternalStorageDirectory();
// Create a new folder in SD Card
File dir = new File(Environment.getExternalStorageDirectory().getPath() + "/Profile");
if (!directory.exists() && !directory.isDirectory()) {
directory.mkdirs();
}
File mypath = new File(dir,"ProfileImage");
saveFile(mypath, bitmap);
} catch (MalformedURLException e) {
} catch (IOException e) {
}
return directory.getAbsolutePath();
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (result != null) {
imageprofile = result;
}
}
private void saveFile(File fileName, Bitmap bmp) {
FileOutputStream outputStream = null;
try {
outputStream = new FileOutputStream(fileName);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); // 100 will be ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
EDIT:
public class ImageUserTask extends AsyncTask<Void,Void,Bitmap> {
String strURL, imageprofile;
Bitmap mBitmap = null;
Context mContext;
private File profileFile;
public ImageUserTask(Context context, String url) {
this.strURL = url;
this.imageprofile = imageprofile;
this.mContext = context;
}
#Override
protected Bitmap doInBackground(Void... params) {
getImageFromUrl(strURL);
return mBitmap;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (result != null) {
Bitmap bitmap = result;
}
}
public Bitmap getImageFromUrl(String urlString) {
try {
URL url = new URL(urlString);
try {
if(mBitmap!=null) {
mBitmap.recycle();
mBitmap=null;
}
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
//Connected to server
connection.connect();
//downloading image
InputStream input = connection.getInputStream();
mBitmap = BitmapFactory.decodeStream(input);
convertBitmapToFile(mBitmap, urlString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return mBitmap;
}
public File convertBitmapToFile(Bitmap bitmap, String fileName) {
ContextWrapper cw = new ContextWrapper(mContext);
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath;
}
}
What can be the reason? I have added Internet permissions too. Please help. Thank you..
class DownloadFile extends AsyncTask<String, Integer, String> {
String strFolderName;
String shareType;
String downloadPath = "";
Activity mContext;
public DownloadFile(Activity mContext) {
this.mContext = mContext;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... aurl) {
int count;
try {
String fileName = "your filename with ext";
Log.d("TAG", fileName);
URL url = new URL("your url");
URLConnection conexion = url.openConnection();
conexion.connect();
String PATH = "your Path you want to store" + "/";
downloadPath = PATH + fileName;
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(downloadPath);
byte data[] = new byte[1024];
while ((count = input.read(data)) != -1) {
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String path) {
super.onPostExecute(path);
}
}
This code is work for me
Use the below methods
public Bitmap getImageFromUrl(String urlString) {
Bitmap bmp = null;
try {
URL url = new URL(urlString);
try {
if(bmp!=null) {
bmp.recycle();
bmp=null;
}
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
convertBitmapToFile(bmp, urlString);
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
return bmp;
}
public File convertBitmapToFile(Bitmap bitmap, String fileName) {
ContextWrapper cw = new ContextWrapper(activityRef.getApplicationContext());
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
File mypath = new File(directory, fileName);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(mypath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
return mypath;
}
Add android Permissions for internet and Storage
Please try this
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
I want to get user's facebook profile picture url and below is code for that.
Code :
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
StringBuilder res = new StringBuilder();
// fetch user profile picture url
URL url = null;
HttpURLConnection httpconn = null;
String strUrl = "http://graph.facebook.com/"
+ fbuser.getFacebookId()
+ "/picture?width=350&height=350";
try {
url = new URL(strUrl);
httpconn = (HttpURLConnection) url
.openConnection();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
BufferedReader input = new BufferedReader(
new InputStreamReader(httpconn
.getInputStream()));
String strLine = null;
while ((strLine = input.readLine()) != null) {
res.append(strLine);
}
input.close();
}
Log.e(TAG, "res : " + res);
JSONObject imageUrlObject = new JSONObject(
res.toString());
fbuser.setImageUrl(imageUrlObject
.getJSONObject("picture")
.getJSONObject("data")
.getString("url"));
// Call a method of an Activity to notify
// user info is received
((RS_LoginActivity) RS_Facebook.this.activity)
.FacebookUserInfoReceived();
// call login api
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
thread.start();
I log the string response and below is the screen shot of how that response looks like.
Any idea why this happens?
The API spec likely changed; use the following workaround:
fbuser.setImageUrl("http://graph.facebook.com/"
+ fbuser.getFacebookId()
+ "/picture?width=350&height=350");
That URL is what got you a JPEG image as of lately, so it's likely the URL you need.
public class Profile extends Activity {
ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
iv= (ImageView)findViewById(R.id.imageView1);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String url = "http://graph.facebook.com/" + fbID+ "/picture?width=800&height=600";
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = loadBitmap(url, bmOptions);
iv.setImageBitmap(bm);
}
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
Bitmap bitmap = null;
InputStream in = null;
try
{
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in, null, options);
in.close();
}
catch (IOException e1) {
}
return bitmap;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}
Here is my code... you'll see where I want to save the Drawable d into the File f location:
ImageView imgView = (ImageView)header.findViewById(R.id.imvCover);
File cacheDir = this.getCacheDir();
File f = new File(cacheDir, itemDict.get("Barcode") + ".jpg");
if (f.exists())
{
Bitmap bmp = BitmapFactory.decodeFile(f.getAbsolutePath());
imgView.setImageBitmap(bmp);
}
else
{
String url = (String)itemDict.get("imageURL");
InputStream is = null;
try {
is = (InputStream) new URL(url).getContent();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Drawable d = Drawable.createFromStream(is, "src");
if (d != null)
{
imgView.setImageDrawable(d);
// TODO: save the drawable into the cache directory
}
else
{
imgView.setImageResource(R.drawable.cam);
}
}
How do I save the Drawable as a .jpg?
Use Bitmap.compress(...), like so:
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream("/someLocation/someFileName.jpg"));
} catch (Exception e) {
//TODO: Handle exception
}
See this SO answer for an example on how to get your cache directory path:
android-download-images-from-server-and-save-them-on-device-cache
And this on conversion from Drawable to Bitmap:
how-to-convert-a-drawable-to-a-bitmap
I have an app that receives qr code from the server. I want to decode it (not with intent and camera) and display the text it contains in my app. I have alredy done this in Java SE with jars from zxing with this code:
private class QRCodeDecoder {
public String decode(File imageFile) {
BufferedImage image;
try {
image = ImageIO.read(imageFile);
} catch (IOException e1) {
return "io outch";
}
// creating luminance source
LuminanceSource lumSource = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(lumSource));
// barcode decoding
QRCodeReader reader = new QRCodeReader();
Result result = null;
try {
result = reader.decode(bitmap);
} catch (ReaderException e) {
return "reader error";
}
return result.getText();
}
}
But on Android, BufferedImage is not found.
Has anyone decoded qr code on android from image stored on the phone?
Tnx.
In android,you can do it this way:
#Override
protected Result doInBackground(Void... params)
{
try
{
InputStream inputStream = activity.getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
if (bitmap == null)
{
Log.e(TAG, "uri is not a bitmap," + uri.toString());
return null;
}
int width = bitmap.getWidth(), height = bitmap.getHeight();
int[] pixels = new int[width * height];
bitmap.getPixels(pixels, 0, width, 0, 0, width, height);
bitmap.recycle();
bitmap = null;
RGBLuminanceSource source = new RGBLuminanceSource(width, height, pixels);
BinaryBitmap bBitmap = new BinaryBitmap(new HybridBinarizer(source));
MultiFormatReader reader = new MultiFormatReader();
try
{
Result result = reader.decode(bBitmap);
return result;
}
catch (NotFoundException e)
{
Log.e(TAG, "decode exception", e);
return null;
}
}
catch (FileNotFoundException e)
{
Log.e(TAG, "can not open file" + uri.toString(), e);
return null;
}
}
Download ZXing from google code, and this class file: ZXing-1.6/zxing-1.6/androidtest/src/com/google/zxing/client/androidtest/RGBLuminanceSource.java can help you.
Quickmark and qr droid actually reads out what the code says, and you can decode barcodes saved on your phone. Hit the menu button when your load the image and select share, find decode qr droid or decode quickmark, and the'll do the magic. I prefer quickmark for reading codes, because it tells me what is typed in the code.