I am new to android.The Image is store in server by Base64 format. so how can i get it from server to My Project and set to my ImageView using Json Object.
Please Help me
Any help will be Appappreciated
Try this:
Convert Url to byte[] first:
byte[] bitmapdata = getByteArrayImage(url);
Method:
private byte[] getByteArrayImage(String url){
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
ByteArrayBuffer baf = new ByteArrayBuffer(500);
int current = 0;
while ((current = bis.read()) != -1) {
baf.append((byte) current);
}
return baf.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
Now convert the byte[] to bitmap
Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata , 0, bitmapdata .length);
And set your bitmap to your ImageView:
img= (ImageView) findViewById(R.id.imgView);
img.setImageBitmap(bitmap );
I found easy solution:
byte[] img = Base64.decode(userHeader.GetImage(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(img, 0, img.length);
imageww.setImageBitmap(getCircleBitmap(bitmap));
Using Apache's commons-io-2.5 lib we can get using this function IOUtils.toByteArray(is)
public static String getByteArrayFromURL(final String url) {
String base64Image = "";
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<String> result = executor.submit(new Callable<String>() {
public String call() throws Exception {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
return Base64.encodeToString(IOUtils.toByteArray(is), Base64.NO_WRAP);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
});
try {
base64Image = result.get();
} catch (Exception exception) {
exception.printStackTrace();
}
return base64Image;
}
Related
I'm receiving URL of images and other data from API and showing images into recyclerview, I want to store images in room database in a byte array format, but I'm getting an error while converting image URL to a byte array. My app is crashing at url.openstream();.
private byte[] getByteArrayImage(String imageUrl) {
URL url = null;
try {
url = new URL(imageUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
}
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
byte[] chunk = new byte[4096];
int bytesRead;
InputStream stream = url.openStream();
while ((bytesRead = stream.read(chunk)) > 0) {
outputStream.write(chunk, 0, bytesRead);
}
url.openStream().close();
} catch (IOException e) {
e.printStackTrace();
return null;
}
return outputStream.toByteArray();
}
There are a couple of problems with your code:
As already noted in a comment, you call openStream() twice.
If an exception occurs, close() won't be called in your code. Use try-with-resources instead.
Propagate exceptions to the caller. The caller will generally want to know the exception message.
Don't ever use printStackTrace(). This is the worst way to report errors.
After the first printStackTrace(), you continue with a null URI, which will cause a NullPointerException.
The method should be static.
Here's how I would write this:
private static byte[] getImageBytes(String imageUrl) throws IOException
{
URL url = new URL(imageUrl);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try (InputStream stream = url.openStream())
{
byte[] buffer = new byte[4096];
while (true)
{
int bytesRead = stream.read(buffer);
if (bytesRead < 0) { break; }
output.write(buffer, 0, bytesRead);
}
}
return output.toByteArray();
}
I recommend below pseudo code to read data from URL:
Thread t = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
URL url = new URL("you'r address");
URLConnection connection = url.openConnection();
InputStream is = connection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
StringBuffer sb = new StringBuffer();
int r;
while((r = isr.read()) != -1)
{
sb.append(r);
}
byte buffer[] = sb.toString().getBytes();
}
catch (MalformedURLException e)
{
e.printStackTrace();
Log.i("tag" , "MalformedURLException"+e.getMessage());
}
catch (IOException e)
{
e.printStackTrace();
Log.i("tag" , "IOException"+e.getMessage());
}
}
});
t.start();
I've already seen
Is it possible to check progress of URLconnection.getInputStream()?
https://stackoverflow.com/a/20120451/5437621
I'm using the following code to download a file from internet:
try {
InputStream is = new URL(pdfUrl).openStream();
byte[] pdfData = readBytes(is);
return pdfData;
} catch (IOException e) {
e.printStackTrace();
return null;
}
public byte[] readBytes(InputStream inputStream) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
return byteBuffer.toByteArray();
}
Is there any method I can get the progress of the file being downloaded ?
The answers I have seen are using a while loop but I don't understand how to use it in this case.
EDIT:
I'm using this in AsyncTask:
protected byte[] doInBackground(String... url) {
pdfUrl = url[0];
try {
InputStream is = new URL(pdfUrl).openStream();
DownloadBytes downloadData = readBytes(is);
byte[] pdfData = downloadData.getBytes();
progress = downloadData.getProgress();
return pdfData;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
How can I adjust publishProgress() in this method ?
I'm trying to grab (with the method below) an image from the internet and do some canvas work with. but sometimes i'm having outOfMemory exception. So i'm wondering if is there a way to load the inputStream directly in the memory card instead of the internal memory.
private Bitmap LoadImageFromWebOperations(String url)
{
try {
InputStream is = (InputStream) new URL(url).getContent();
Drawable d = Drawable.createFromStream(is, "src name");
bitmap = ((BitmapDrawable)d).getBitmap().copy(Config.ARGB_8888, true);
return bitmap;
}catch (Exception e) {
System.out.println("Exc="+e);
return null;
}
}
the logcat says that the exception is due to that line :
Drawable d = Drawable.createFromStream(is, "src name");
Thx in advance!
I took this code from Fedor Vlasov's lazylist demo:
Lazy load of images in ListView.
First you need to create a function to copy your input stream to file output stream:
public static 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){}
}
Then get a cache folder:
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED))
cacheDir=new File(android.os.Environment.getExternalStorageDirectory(),"MyCacheDir");
else
cacheDir=context.getCacheDir();
if(!cacheDir.exists())
cacheDir.mkdirs();
Then load your bitmap:
private Drawable getBitmap(String url)
{
String filename=URLEncoder.encode(url);
File f= new File(cacheDir, filename);
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(f);
CopyStream(is, os);
os.close();
Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(f));
return new BitmapDrawable(bitmap);
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
I'm trying to get a image from particular URL but it throwsFileNotFoundException. If I try to open the url from my browser, i can see the images. Please help. Below is my code. Thanks.
String fileURL = "http://sposter.smartag.my/images/KFC_Voucher.jpg";
String FILENAME = "caldophilus.jpg";
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
File root = Environment.getExternalStorageDirectory();
FileOutputStream f = new FileOutputStream(new File(root, FILENAME));
InputStream x=c.getInputStream();
int size=x.available();
byte b[]= new byte[size];
x.read(b);
f.write(b);
f.flush();
f.close();
i try this and its work fine. Thanks.
URL url = new URL(fileURL);
URLConnection conexion = url.openConnection();
conexion.connect();
int lenghtOfFile = conexion.getContentLength();
Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/caldophilus.jpg");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
Try this:
BufferedInputStream inputStream = null;
OutputStream out = null;
String fileName = null;
String path = null;
File savedFile = null;
try
{
// Replace your URL here.
URL fileURL = new URL("http://enter.your.url.here");
URLConnection connection = fileURL.openConnection();
connection.connect();
inputStream = new java.io.BufferedInputStream(connection.getInputStream());
// Replace your save path here.
File fileDir = new File("path/to/save");
fileDir.mkdirs();
savedFile = new File("path/to/save", fileName);
out = new FileOutputStream(savedFile);
byte buf[] = new byte[1024];
int len;
long total = 0;
while ((len = inputStream.read(buf)) != -1)
{
total += len;
out.write(buf, 0, len);
}
out.close();
inputStream.close();
}
catch (Exception)
{
}
Try the below code. It should work!
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
public class DownloadManager {
public static void downLoadImage(String imageURL, String destinationFileName) throws IOException {
URL url = new URL(imageURL);
InputStream inputStream = url.openStream();
OutputStream outputStream = new FileOutputStream(destinationFileName);
byte[] byteData = new byte[2048];
int length;
while((length=inputStream.read(byteData))!=-1) {
outputStream.write(byteData, 0, length);
}
inputStream.close();
outputStream.close();
}
public static void main(String[] args) throws IOException {
String imageURL = "http://sposter.smartag.my/images/KFC_Voucher.jpg";
String destinationFileName = "C:/Users/sarath_sivan/Desktop/caldophilus.jpg";
downLoadImage(imageURL, destinationFileName);
}
}
Try this at once -
try {
url = paths[0];
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
int length = connection.getContentLength();
InputStream is = (InputStream) url.getContent();
byte[] imageData = new byte[length];
int buffersize = (int) Math.ceil(length / (double) 100);
int downloaded = 0;
int read;
while (downloaded < length) {
if (length < buffersize) {
read = is.read(imageData, downloaded, length);
} else if ((length - downloaded) <= buffersize) {
read = is.read(imageData, downloaded, length
- downloaded);
} else {
read = is.read(imageData, downloaded, buffersize);
}
downloaded += read;
publishProgress((downloaded * 100) / length);
}
Bitmap bitmap = BitmapFactory.decodeByteArray(imageData, 0,
length);
if (bitmap != null) {
Log.i(TAG, "Bitmap created");
} else {
Log.i(TAG, "Bitmap not created");
}
is.close();
return bitmap;
} catch (MalformedURLException e) {
Log.e(TAG, "Malformed exception: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
And, just take a look at here
In ...
FileOutputStream f = new FileOutputStream(new File(root, FILENAME));
Try replacing FILENAME with fileURL.
Also, at which line is the exception thrown? That would help.
String fileURL = "http://sposter.smartag.my/images/KFC_Voucher.jpg";
String FILENAME = "caldophilus.jpg";
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
//c.setDoOutput(true); =========== remove this;
c.connect();
I have this method that downloads .csv files from yahoo finance and saves them locally. It is accessed during a loop so it is downloading many files from a list. However sometimes a symbol is entered incorrectly, no longer exists, or the connection times out. How can I amend this method so that connection time outs are retried and incorrect symbols (meaning the url does not work) are just skipped over without ending the program?
public static void get_file(String symbol){
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol;
String destination = "C:/"+symbol+"_table.csv";
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(finance_url);
outStream = new BufferedOutputStream(new FileOutputStream(destination));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
}catch (Exception e) {
System.out.println("Error while downloading "+symbol);
e.printStackTrace();
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
Why not call the method again when an exception is thrown. You can narrow down the exception type to indicate when a retry should be initiated.
public static void get_file(String symbol){
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
String finance_url = "http://ichart.finance.yahoo.com/table.csv?s="+symbol;
String destination = "C:/"+symbol+"_table.csv";
try {
URL Url;
byte[] buf;
int ByteRead,ByteWritten=0;
Url= new URL(finance_url);
outStream = new BufferedOutputStream(new FileOutputStream(destination));
uCon = Url.openConnection();
is = uCon.getInputStream();
buf = new byte[size];
while ((ByteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, ByteRead);
ByteWritten += ByteRead;
}
}catch (Exception e) {
getFile(symbol);
}finally {
try {
is.close();
outStream.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}