Hi every body i want store byte format of image in my database from url. I am using this code
URL url = new
URL("http://images.11bestbuy.com/images/small_17385013870957.jpg");
InputStream anyfile = url.openStream();
But it is showing error for me.
You can decode a Bitmap and then convert it to a byte array:
public byte[] downloadImage() throws Exception{
URL url = new URL("http://images.11bestbuy.com/images/small_17385013870957.jpg");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
con.setReadTimeout(10000);
con.setConnectTimeout(10000);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
Bitmap b = BitmapFactory.decodeStream(con.getInputStream());
b.compress(Bitmap.CompressFormat.JPEG,100,bos);
} finally {
con.disconnect();
}
return bos.toByteArray();
}
You can store byte array in BLOB type record of a SQLite database.
Try this it is working for me
static private Bitmap downloadBitmap(String url) throws IOException {
HttpUriRequest request = new HttpGet(url);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
System.out.println("kjklcmklxc");
HttpEntity entity = response.getEntity();
byte[] bytes = EntityUtils.toByteArray(entity);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
bytes.length);
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, byt_aary_outpt_strm);
dh.delete(DatabaseHelper.Image_handler, null, null);
bitmapdata = byt_aary_outpt_strm.toByteArray();
System.out.println("bitmap of image converted image");
for(int i =0 ; i<bitmapdata.length;i++){
convert_save_byte_str = convert_save_byte_str+bitmapdata[i];
}
System.out.println("njdsfnh"+convert_save_byte_str);
ContentValues userdetailValues = new ContentValues();
userdetailValues.put("image_byte", convert_save_byte_str);
System.out.println("between put and insert");
dh.insert(DatabaseHelper.Image_handler, null, userdetailValues);
cursor = dh.rawQuery("SELECT _id, image_byte FROM image_database",null);
int i=0;
if (cursor.moveToFirst()) {
do {
// get the data into array,or class variable
bb = cursor.getBlob(cursor.getColumnIndex(DatabaseHelper.Image_handeler_column));
//System.out.println("productid"+data);
//intent.putExtra("product_id", data);
System.out.print("bytengkfgkjgk"+bb[i]);
i++;
} while (cursor.moveToNext());
}
return bitmap;
} else {
throw new IOException("Download failed, HTTP response code "
+ statusCode + " - " + statusLine.getReasonPhrase());
}
}
Related
This is my first question on stackoverflow.
My problem is: i'm trying to convert byte[] into image. The byte[] comes from JSON and it's in this format:
"4oCwUE5HDQoaCgAAAA1JSERSAAAAfwAAAFAIBgAAADBHwqrDsAAAAAlwSFlzAAAAJwAAACcBKgnigJhPAAAgAElEQVR4xZPCrMK9ecWSZcOZfcOfw7c5w5vCvW/CqXp..." it goes for another 100 lines.
The code where the problem occurs:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(PlayersListActivity.URL);
httpPost.setEntity(new UrlEncodedFormEntity(parameters, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
BufferedHttpEntity bufferedEntity = new BufferedHttpEntity(httpEntity);
// if this is null the web service returned an empty page
if(httpEntity == null) // response is empty so exit out
return null;
String jsonString = EntityUtils.toString(bufferedEntity);
// again some simple validation around the returned string
if(jsonString != null && jsonString.length() != 0) // checking string returned from service to grab id
{
JSONArray jsonArray = new JSONArray(jsonString);
for(int i=0; i< jsonArray.length(); i++)
{
HashMap<String, Object> map = new HashMap<String, Object>();
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
byte[] images = jsonObject.getString("image").getBytes();
Bitmap btm = BitmapFactory.decodeByteArray(images, 0, images.length);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
btm.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bitmap btm2 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageBitmap(btm2);
map.put("name", name.toString());
map.put("image", images.toString());
Log.d("JSON OBJECTS:", jsonObject.toString());
Log.d("WHATS IN MAP:", map.toString());
playersList.add(map);
And ofcourse error that I'm getting in LogCat:
SkImageDecoder:: Factory returned null.
java.lang.NullPointerException
and it points out on this line:
Bitmap btm2 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
I have done reseach but nothing really points on what I'm missing.
Any ideas??
Thanks!!
4oCwUE5HDQoaCgAAAA1JSERSAAAAfwAAAFAIBgAAADBHwqrDsAAAAAlwSFlzAAAAJwAAACcBKgnigJhPAAAgAElEQVR4xZ
PCrMK9ecWSZcOZfcOfw7c5w5vCvW/CqXp..." it goes for another 100 lines.
Its seems like its not a byte[] but its a Base64 String
So try like
String base64 = jsonObject.getString("image");
byte[] decodedString = Base64.decode(base64, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
image.setImageBitmap(decodedByte);
Hope this help you.
**Your web service is the UTF-8 decoder**
String str=[Base64];
str = URLDecoder.decode(str, "UTF-8");
ImageView imgView.setImageBitmap(StringToBitMap(str));
public static Bitmap StringToBitMap(String image) {
try {
byte[] encodeByte = Base64.decode(image.getBytes(), Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(encodeByte, 0,
encodeByte.length);
return bitmap;
} catch (Exception e) {
e.getMessage();
return null;
}
}
That such a good night, I write to ask if I could help and to coregir the following code, which right through a listView and presslong, took the path of the file, to try and turn the service:
of:
http://www.convertapi.com/excel-pdf-api
I have not to use a webview, or could use a hidden way
thank
code is:
mPrefs = getSharedPreferences("RutaPath", Context.MODE_PRIVATE);
String rutasave = mPrefs.getString("Externa", "");
String resultcode = "0";
HttpPost httppost = new HttpPost("http://do.convertapi.com/Excel2Pdf/json");
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
// For File parameters
file=new File(rutasave+"prueba.xls");
//Toast.makeText(this,"cargando: " +rutasave+"prueba.xls",Toast.LENGTH_SHORT).show();
outputDir=rutasave;
entity.addPart("file", new FileBody(file, "binary/octet-stream"));//"file"
httppost.setEntity( entity );
HttpClient httpclient = new DefaultHttpClient();
// return new Boolean(true);//eliminar despues
try {
HttpResponse response = httpclient.execute(httppost);
Header rcHeader = response.getFirstHeader("result");
if(rcHeader != null){
resultcode = rcHeader.getValue();
if("True".equals(resultcode)){
filesize = response.getFirstHeader("filesize").getValue();
filename = response.getFirstHeader("OutputFileName").getValue();
//Toast.makeText(this,"Archivo: " +filename,Toast.LENGTH_SHORT).show();
HttpEntity hentity = response.getEntity();
if(hentity != null){
InputStream istream = hentity.getContent();
File file = new File(outputDir+filename+".pdf");//outputDir File.separator
FileOutputStream ostream = new FileOutputStream(file);
byte[] b = new byte[1024];
int num = 0;
while( (num = istream.read(b, 0, b.length)) > 0)
ostream.write(b, 0, num);
istream.close();
ostream.flush();
ostream.close();
return new Boolean(true);
}
}
}
} catch (ClientProtocolException e) {
latest update.. i have codes for uploading image.. but i do not know whats going to do for this code..? source code from http://monstercoda.wordpress.com/2012/04/15/android-image-upload-tutorial-part-i/
codes are the following:
public class MainActivity extends Activity {
Uri currImageURI;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button gallery_btn = (Button)findViewById(R.id.gallerybtn);
gallery_btn.setOnClickListener(new OnClickListener(){
public void onClick(View view){
//to open up a gallery browser
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,"Select Picture.."),1);
(getRealPathFromURI(currImageURI);
}
});
}
// To handle when an image is selected from the browser
public void onActivityResult(int requestCode, int resultCode, Intent data){
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
// currImageURI is the global variable I’m using to hold the content:
currImageURI = data.getData();
String s = ("Current image Path is ----->" + getRealPathFromURI(currImageURI));
TextView tv_path = (TextView) findViewById(R.id.path);
tv_path.setText(getRealPathFromURI(currImageURI));
}
HttpUploader uploader = new HttpUploader();
try {
uploader.execute(getRealPathFromURI(currImageURI));
}
}
//Convert the image URI to the direct file system path of the image file
public String getRealPathFromURI( Uri contentUri) {
String [] proj={MediaStore.Images.Media.DATA};
android.database.Cursor cursor = managedQuery(contentUri,
proj, // Which columns to return
null, // WHERE clause; which rows to return (all rows)
null, // WHERE clause selection arguments (none)
null); // Order-by clause (ascending by name)
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String c = cursor.getString(column_index);
return c;
}
}
my httpUploader is simple as simple as they provide:
public class HttpUploader extends AsyncTask<String, Void, String> {
protected String doInBackground(String... path) {
String outPut = null;
for (String sdPath : path) {
Bitmap bitmapOrg = BitmapFactory.decodeFile(sdPath);
ByteArrayOutputStream bao = new ByteArrayOutputStream();
//Resize the image
double width = bitmapOrg.getWidth();
double height = bitmapOrg.getHeight();
double ratio = 400/width;
int newheight = (int)(ratio*height);
System.out.println("———-width" + width);
System.out.println("———-height" + height);
bitmapOrg = Bitmap.createScaledBitmap(bitmapOrg, 400, newheight, true);
//Here you can define .PNG as well
bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 95, bao);
byte[] ba = bao.toByteArray();
String ba1=Base64.encodeBytes(ba);
String k = "uploading image now ——–" + ba1 ;
Log.e("k contains", k);
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
//store path for image name and id for each profile id.
nameValuePairs.add(new BasicNameValuePair("image", ba1));
nameValuePairs.add(new BasicNameValuePair("path", sdPath));
nameValuePairs.add(new BasicNameValuePair("id", id));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("192.168.1.1/upload.php"); // which request for $_POST['image'];
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// print responce
outPut = EntityUtils.toString(entity);
Log.i("GET RESPONSE—-", outPut);
//is = entity.getContent();
Log.e("log_tag ******", "good connection");
bitmapOrg.recycle();
} catch (Exception e) {
Log.e("log_tag ******", "Error in http connection " + e.toString());
}
}
return outPut;
}
}
PHP file saving to the database:
if (isset($base)) {
$base = $_REQUEST["image"];
$filepath = $_REQUEST["path"];
$id = $_REQUEST["id"];
$image_name = "/image/".$filepath;
// base64 encoded utf-8 string
$binary = base64_decode($base);
// binary, utf-8 bytes
header("Content-Type: bitmap; charset=utf-8");
$file = fopen($image_name, "wb");
fwrite($file, $binary);
fclose($file);
$result = "UPDATE profile SET image = '$image_name' WHERE RID = '$id'");
if(mysql_affected_rows > 0){
echo json_encode ("success!");
}else{
echo json_encode ("failed!");
}
} else {
die("No POST");
}
?>
or if the code is not appropriate... any guidnce can be provided for beginner? there are too many versions of code out there.. and i can slightly understand this because it is simpler than others.
Remove the .get() from your asynctask call.
Put HttpUploader uploader = new HttpUploader(); and Object image_name = uploader.execute(getRealPathFromURI(currImageURI)); without the .get() in onActivityResult(). Because only in onActivityResult() you know the filename.
i am trying to develop an OCR app, which will recognize the content of Camera pic , but getting a response "This Image Is too Big",i tried to resize the image,,, but still not happening. My code of OCR is this
public class weocr {
String response;
#SuppressWarnings("unused")
private String selectedpath;
weocr(String selectedpath) throws UnsupportedEncodingException, ParseException, ClientProtocolException, IOException
{
String url="http://appsv.ocrgrid.org/cgi-bin/weocr/submit_tesseract.cgi";
response="";
this.selectedpath=selectedpath;
HttpClient client = new DefaultHttpClient();
client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpPost post=new HttpPost(url);
MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
//test start
try {
File imgFile = new File(selectedpath);
int h = 200; // height in pixels
int w = 200; // width in pixels
Bitmap bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
Bitmap bm1 = Bitmap.createScaledBitmap(bm, h, w, true);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bm.compress(CompressFormat.JPEG, 50, bos);
byte[] data = bos.toByteArray();
ByteArrayBody bab = new ByteArrayBody(data, "testbin.png");
//test end
entity.addPart( "userfile", bab);
// For usual String parameters
entity.addPart( "outputencoding", new StringBody("utf-8"));
entity.addPart( "outputformat", new StringBody("txt"));
post.setEntity( entity );
HttpResponse response = client.execute(post);
BufferedReader reader = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String sResponse;
StringBuilder s = new StringBuilder();
while ((sResponse = reader.readLine()) != null) {
s = s.append(sResponse);
}
this.response=new String(s.toString());
//System.out.println("Response: " + s);
// Here we go!
//String response = EntityUtils.toString( client.execute( post ).getEntity(), "UTF-8" );
//client.getConnectionManager().shutdown();
//System.out.println(response);
//Toast toast=Toast.makeText(getApplicationContext(), response, Toast.LENGTH_LONG);
//toast.show();
}
catch (Exception e) {
Log.e(e.getClass().getName(), e.getMessage());
}
}
}
I have an android application that needs to receive several pictures from the webservice.
But how to do this?
In my webservice i'm currently sending only 1 image as a byte[].
public static byte[] GetMapPicture(string SeqIndex)
{
try
{
byte[] maps;
InterventionEntity interventie = new InterventionEntity(long.Parse(SeqIndex));
MyDocumentsCollection files = interventie.Location.MyDocuments;
maps = null;
foreach (MyDocumentsEntity file in files)
{
if (file.SeqDocumentType == (int)LocationDocumentType.GroundPlanDocument && file.File.Filename.EndsWith(".jpg"))
maps = (file.File.File);
}
return maps;
} catch (Exception e) {
Log.Error(String.Format("Map not send, {0}", e));
return null;
}
}
The byte[] is returned from my webservice.
But in my android project the bitmap is not decoded and therefor null.
public Bitmap getPicture(String message, String url, Context context) throws IOException{
HttpClient hc = MySSLSocketFactory.getNewHttpClient();
Log.d(MobileConnectorApplication.APPLICATION_TAG, "NETWORK - Message to send: "+ message);
HttpPost p = new HttpPost(url);
Bitmap picture;
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(httpParams, threeMinutes );
p.setParams(httpParams);
try{
if (message != null)
p.setEntity(new StringEntity(message, "UTF8"));
}catch(Exception e){
e.printStackTrace();
}
p.setHeader("Content-type", "application/json");
HttpContext httpcontext = new BasicHttpContext();
httpcontext.setAttribute(ClientContext.COOKIE_STORE, MobileConnectorApplication.COOKIE_STORE);
try{
HttpResponse resp = hc.execute(p,httpcontext);
InputStream is = resp.getEntity().getContent();
picture = BitmapFactory.decodeStream(is); //here is goes wrong
int httpResponsecode = resp.getStatusLine().getStatusCode() ;
checkResponse(url, message, "s", httpResponsecode);
Log.d(MobileConnectorApplication.APPLICATION_TAG, String.format("NETWORK - Response %s", httpResponsecode));
} finally{
}
return picture;
}
Can anyone help me on this?
assuming incomingbytearray is a byte array,
Bitmap bitmapimage = BitmapFactory.decodeByteArray(incomingbytearray, 0, incomingbytearray.length);
String filepath = "/sdcard/xyz.png";
File imagefile = new File(filepath);
FileOutputStream fos = new FileOutputStream(imagefile);
bitmapimage.compress(CompressFormat.PNG, 100, fos);
fos.flush();
fos.close();
This should be fine.
EDIT: input stream to bytearray,
InputStream in = new BufferedInputStream(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();
conversion code from Android: BitmapFactory.decodeByteArray gives pixelated bitmap