I am new to android and I need to save image from url into db and fetch it from db. I an converting image from link into byte array but getting the following error:
Cannot Resolve ByteArrayBuffer
This is the code:
private byte[] getLogoImage(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;
}
Update your method getLogoImage() as below.
Use AsyncTask and call this method from doInBackground().
Here is the working code. Try this:
private byte[] getLogoImage(String url) {
try {
URL imageUrl = new URL(url);
URLConnection ucon = imageUrl.openConnection();
InputStream is = ucon.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int read = 0;
while ((read = is.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, read);
}
baos.flush();
return baos.toByteArray();
} catch (Exception e) {
Log.d("ImageManager", "Error: " + e.toString());
}
return null;
}
Try like this
Bitmap bm = null;
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bm = BitmapFactory.decodeStream(bis);
byte[] imageArray = getBytes(bm);
and after this use below method
public static byte[] getBytes(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
return stream.toByteArray();
}
Use This
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 3;
Bitmap bitmap = BitmapFactory.decodeFile(url,
options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 50, stream);
byte[] byte_arr = stream.toByteArray();
Related
Hi I am a New to Android. Can Some One Describe the way if any of storing a Image to Android database & retrieve it ?
Look at this tutorial...
http://www.tutorialforandroid.com/2009/10/how-to-insert-image-data-to-sqlite.html
and you can use this code :
for storing image :
Map<String, byte[]> hh = new HashMap<String, byte[]>();
String hi = "http://i.stack.imgur.com/TLjuP.jpg";
byte[] logoImagedata = getLogoImage(hi);
hh.put("img",logoImagedata);
for retriving :
byte[] imageByteArray = hh.get("img");
ByteArrayInputStream imageStream = new ByteArrayInputStream(imageByteArray);
Bitmap theImage= BitmapFactory.decodeStream(imageStream);
and getLogoImage:
private byte[] getLogoImage(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;
}
}
I hope this help you .
I have establish WiFi connection between two android devices. Now I want to send Bitmap from server to client. I use the following code to send Bitmap from server to Client:
server code:
outputStream = hostThreadSocket.getOutputStream();
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 20,stream);
byte[] byteArray = stream.toByteArray();
String str =Base64.encodeToString(byteArray,0);
msgReply+=" "+str;
outputStream.write(str.getBytes());
outputStream.flush();
outputStream.close();
client code:
socket = new Socket(dstAddress, dstPort);
ByteArrayOutputStream byteArrayOutputStream =
new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int bytesRead;
InputStream inputStream = socket.getInputStream();
while ((bytesRead = inputStream.read(buffer)) != -1){
byteArrayOutputStream.write(buffer, 0, bytesRead);
response += byteArrayOutputStream.toString();
}
byte[] temp_arr = new byte[1024];
String[] safe = response.split("=");
try{
temp_arr=Base64.decode(safe[0], 0);
}catch (Exception e){
e.printStackTrace();
}
Bitmap bmp = BitmapFactory.decodeByteArray(temp_arr,0,temp_arr.length);
ImageView img=(ImageView)findViewById(R.id.imgView);
img.setImageBitmap(bmp);
I have created a server which receives byte array from a c++ client, the client send image as uchar array(using opencv) and on the android I am receiving the data correctly. The server on android store data to byte array and I need to convert this byte array to Bitmap. But I am getting null Bitmap after using BitmapFactory.decodeByteArray.
Here is my server code which receives data and store in to byte array
class imageReciver extends Thread {
public static byte imageByte[];
private ServerSocket serverSocket;
InputStream in;
int imageSize=921600;//expected image size 640X480X3
public imageReciver(int port) throws IOException{
serverSocket = new ServerSocket(port);
}
public void run()
{
Socket server = null;
server = serverSocket.accept();
in = server.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte buffer[] = new byte[1024];
int remainingBytes = imageSize; //
while (remainingBytes > 0) {
int bytesRead = in.read(buffer);
if (bytesRead < 0) {
throw new IOException("Unexpected end of data");
}
baos.write(buffer, 0, bytesRead);
remainingBytes -= bytesRead;
}
in.close();
imageByte = baos.toByteArray();
baos.close();
server.close();
//Here conver byte array to bitmap
Bitmap bmp = BitmapFactory.decodeByteArray(imageByte, 0,imageByte.length);
return;
}
}
I seems your code is not correct, try this:
try {
URL myURL = new URL(url);
final BufferedInputStream bis = new BufferedInputStream(myURL.openStream(), 1024);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
BufferedOutputStream out = new BufferedOutputStream(dataStream,1024);
copy(bis, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options bfo = new BitmapFactory.Options();
bfo.inSampleSize = 2;
Bitmap bm = BitmapFactory.decodeByteArray(data, 0, data.length, bfo);
bis.close();
//use the bitmap...
}
catch (Exception e) {
//handle ex
}
Through web service i am writing each image in to a JPG file(in sdcard- "mnt/sdcard/img.jpg") and showing the images in to a coverflow view.i am getting the first image but when it comes to the second and other images i am getting outofmemoryerrorr.
below i have given the code to get the image from url
public Bitmap getImageDirectHit(String directHitUrl){
Bitmap bmImg;
String fileUrl=directHitUrl;
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
bmImg = null;
HttpURLConnection conn= (HttpURLConnection)myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
//int length = conn.getContentLength();
InputStream is = conn.getInputStream();
//conn.disconnect();
// BufferedInputStream bis = new BufferedInputStream(is);
// ByteArrayBuffer byteArrayBuffer = new ByteArrayBuffer(50);
// int current = 0;
// while ((current = bis.read()) != -1) {
// byteArrayBuffer.append((byte) current);
// }
//
File nf = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
FileOutputStream fos = new FileOutputStream(nf);
//byte[] buf = new byte[2048];
//int n;
// fos.write(bitmapdata, 0, bitmapdata.length);
byte[] bufu=new byte[20];
int len = 0;
while((len = is.read(bufu))>0) {
fos.write(bufu);
}
fos.close();
fos = null;
// ByteArrayOutputStream bos = new ByteArrayOutputStream();
// int next = is.read();
// while (next > -1) {
// bos.write(next);
// next = is.read();
// }
// bos.flush();
// byte[] result = bos.toByteArray();
// bos.close();
// bos = null;
Bitmap tempBitmap =
BitmapFactory.decodeFile(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
//Bitmap tempBitmap = BitmapFactory.decodeByteArray(result, 0, result.length);
//result = null;
bmImg = Bitmap.createScaledBitmap(tempBitmap, 150, 180, true);
tempBitmap.recycle();
tempBitmap = null;
// bmImg = BitmapFactory.decodeStream(is);
// Log.i("Byte Array Size", ":"+byteArrayBuffer.length());
// bis.close();
is.close();
// bis = null;
is = null;
return bmImg;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}
I need to download a single image at time from the Internet and then save it on the SD card. How do I do it? I have made an attempt, but when I try to view that downloaded image, it shows the message, "No Preview Available". Please see my code below:
public class ImgDownloader {
private static final int IO_BUFFER_SIZE = 4 * 1024;
public static final byte[] downloadImage(String imgURL) {
byte[] data = null;
try {
Log.v("Down", "1");
InputStream in = null;
BufferedOutputStream out = null;
in = new BufferedInputStream(new URL(imgURL).openStream(), 8 * 1024);
Log.v("Down", "2");
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
Log.v("Down", "3");
data = dataStream.toByteArray();
// bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Log.v("Down", "4");
} catch (Exception ex) {
ex.printStackTrace();
// System.out.println("Exception in Image Downloader .."
// +ex.getMessage());
}
return data;
}
private static void copy(InputStream in, OutputStream out)
throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
}
Note:
i have download the image from the SSL connection.
Any ideas? Thanks in advance.
You can try something like
try{
URL url = new URL(downloadUrl); //you can write here any link
File file = new File(absolutePath); //Something like ("/sdcard/file.mp3")
//Create parent directory if it doesn't exists
if(!new File(file.getParent()).exists())
{
System.out.println("Path is created " + new File(file.getParent()).mkdirs());
}
file = new File(absolutePath); //Something like ("/sdcard/file.mp3")
file.createNewFile();
/* Open a connection to that URL. */
URLConnection ucon = url.openConnection();
/*
* Define InputStreams to read from the URLConnection.
*/
InputStream is = ucon.getInputStream();
/*
* Read bytes to the Buffer until there is nothing more to read(-1).
*/
FileOutputStream fos = new FileOutputStream(file);
int size = 1024*1024;
byte[] buf = new byte[size];
int byteRead;
while (((byteRead = is.read(buf)) != -1)) {
fos.write(buf, 0, byteRead);
bytesDownloaded += byteRead;
}
/* Convert the Bytes read to a String. */
fos.close();
}catch(IOException io)
{
networkException = true;
continueRestore = false;
}
catch(Exception e)
{
continueRestore = false;
e.printStackTrace();
}
Make the appropriate changes according to your requirement. I use the same code for downloading files from internet and saving it to SDCard.
Hope it helps !!