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());
}
}
}
Related
I'm developing a app, this one send pictures from sd-card but now I need to send some parameters, how can I do this one?
// Open a HTTP connection to the URL
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
//dos.writeBytes (urlParameters);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
thanks a lot!
you can use MultiPartEntity with the help of it you can upload multiple files as well as parameters. this may help.
You can pass file and paramas in multipartentity like this :
public String reportCrime(String uploadFile, int userid, int crimetype,
String crimedetails, String lat, String longi, String reporteddate) {
String url;
MultipartEntity entity;
try {
url = String.format(Constant.SERVER_URL
+ "push_notification/reportCrime.php");
entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
//
File file = new File(uploadFile);
if (!file.equals("Image not Provided.")) {
if (file.exists()) {
Bitmap bmp = BitmapFactory.decodeFile(uploadFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(CompressFormat.JPEG, 70, bos);
InputStream in = new ByteArrayInputStream(bos.toByteArray());
ContentBody foto = new InputStreamBody(in, "image/jpeg", uploadFile);
entity.addPart("image", foto);
}
} else {
FormBodyPart image = new FormBodyPart("image", new StringBody(
""));
entity.addPart(image);
}
FormBodyPart userId = new FormBodyPart("userId", new StringBody(
String.valueOf(userid)));
entity.addPart(userId);
FormBodyPart crimeType = new FormBodyPart("crimetype",
new StringBody(String.valueOf(crimetype)));
entity.addPart(crimeType);
FormBodyPart crimeDetails = new FormBodyPart("crimedetail",
new StringBody(crimedetails));
entity.addPart(crimeDetails);
FormBodyPart latittude = new FormBodyPart("latittude",
new StringBody(lat));
entity.addPart(latittude);
FormBodyPart longitude = new FormBodyPart("longitude",
new StringBody(longi));
entity.addPart(longitude);
FormBodyPart reportedDate = new FormBodyPart("reporteddatetime",
new StringBody(reporteddate));
entity.addPart(reportedDate);
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
return "error";
}
HttpParams httpParams = new BasicHttpParams();
HttpContext httpContext = new BasicHttpContext();
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
HttpConnectionParams.setSoTimeout(httpParams, 10000);
try {
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(entity);
client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(response
.getEntity().getContent()));
StringBuffer sb = new StringBuffer();
String line = null;
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
result = sb.toString();
} finally {
if (in != null)
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
I want to upload images to server.
Here is the code,
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(Constants.yigit);
Charset chars = Charset.forName("UTF-8"); // Setting up the encoding
MultipartEntity reqEntity = new MultipartEntity();
StringBody jsonBody = new StringBody(getNewDemandRequestParams(), "application/json",null);
FormBodyPart jsonBodyPart = new FormBodyPart("data", jsonBody);
reqEntity.addPart(jsonBodyPart);
if (getMainActivity().getImagesSavedData(0).size() > 0) {
for (int i = 0; i < getMainActivity().getImagesSavedData(0).size(); i++) {
File _file = new File(getMainActivity().getImagesSavedData(0).get(i).getFilePath());
FileBody _fileBody = new FileBody(_file, "image/jpg", "UTF-8");
FormBodyPart fileBodyPart = new FormBodyPart(getMainActivity().getImagesSavedData(0).get(i).getImageName().replace(".jpg", ""), _fileBody);
reqEntity.addPart(fileBodyPart);
reqEntity.addPart(getMainActivity().getImagesSavedData(0).get(i).getImageName().replace(".jpg",""), _fileBody);
}
}
post.setEntity(reqEntity);
String result = EntityUtils.toString(reqEntity);
Log.e("rsul", result);
HttpResponse response = client.execute(post);
resEntity = response.getEntity();
final String response_str = EntityUtils.toString(resEntity);
}
But the problem is jsonBodyPart is including slashes.
Request body like this:
{"data"=>"{\"action\":\"YENITALEP\",\"app\":{\"version\":\"verisyon\"},\"data\":{\"invoices\":[{\"imageName\":\"1395914025134\",\"note\":\"\",\"type\":\"FATURA\",\"typeNo\":\"0\"}],\"note\":\"\",\"notification\":[{\"type\":\"BeniAray?n\",\"typeNo\":\"0\"}]},\"device\":{\"hardwareModel\":\"m7\",\"model\":\"HTC
One\",\"systemVersion\":\"4.4.2\",\"uid\":\"00000000-7f39-faab-b500-7f280e9b4fed\"},\"timestamp\":\"Date(1391073711000+0200)\"}",
"1395914025134"=>#,
#original_filename="1395914025134.jpg", #content_type="image/jpg;
charset=UTF-8", #headers="Content-Disposition: form-data;
name=\"1395914025134\";
filename=\"1395914025134.jpg\"\r\nContent-Type: image/jpg;
charset=UTF-8\r\nContent-Transfer-Encoding: binary\r\n">}
How can I post a complex json object and images using multipart? Thanks for help
check once this code iam using this one for uploading images to server
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(urls[0]);
MultipartEntity multipartContent = new MultipartEntity();
for(int i=0;i<allimagespath.size();i++){
Bitmap bm = ShrinkBitmap(allimagespath.get(i), 140, 140);
String format = allimagespath.get(i).substring((allimagespath.get(i).lastIndexOf(".")+1) , allimagespath.get(i).length());
Bitmap bit=Bitmap.createScaledBitmap(bm, 140, 140, true);
ByteArrayOutputStream blob = new ByteArrayOutputStream();
if(format.equalsIgnoreCase("png")){
bit.compress(CompressFormat.PNG, 100 , blob);
}else{
bit.compress(CompressFormat.JPEG, 100 , blob);
}
bitmapdata = blob.toByteArray();
ByteArrayBody thumbbmp = new ByteArrayBody(bitmapdata, "thumb."+format);
FileBody bin2 = new FileBody(new File(allimagespath.get(i)));
multipartContent.addPart("uploaded_file["+i+"]", bin2);
multipartContent.addPart("uploaded_thumb["+i+"]", thumbbmp);
}
multipartContent.addPart("count", new StringBody(""+allimagespath.size()));
postRequest.setEntity(multipartContent);
HttpResponse response = httpClient.execute(postRequest);
HttpEntity entity = response.getEntity();
is = entity.getContent();
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) {
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());
}
}
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