I want to send an Image to a localhost using a button in android a android app.At localhost that image pass to a model developed in python.
After do a process using the image,the model give an output to the android app. That result getting part is working fine.
I want to know how to do the image sending part ?
or suggestion for another way to do that process.
This is the code in the model that get an image which we copy to test folder in the pc. I want to develop this to get image from android app .
def process_test_data():
testing_data = []
for img in tqdm(os.listdir(TEST_DIR)):
path = os.path.join(TEST_DIR,img)
img_num = img.split('.')[0]
img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)
img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))
testing_data.append([np.array(img), img_num])
print("\n****testing_data********",testing_data)
shuffle(testing_data)
np.save('test_data.npy', testing_data)
return testing_data
It really depends on what library you are using to connect to the internet. But for sending pictures, I would suggest first to convert it to Base64 text and send that. Python will sure know how to deal with it.
fun bitmapToBase64StringInline(bitmap: Bitmap): String {
val byteArrayOutputStream = ByteArrayOutputStream()
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, byteArrayOutputStream)
val bytes = byteArrayOutputStream.toByteArray()
return android.util.Base64.encodeToString(bytes, Base64.NO_WRAP)
}
Also, it is good to do it in a separate thread and watch out for OOM exception when using large images.
To send it, use some good connection library like OkHttp, Volley, Retrofit etc. Or, just implement kinda basic AsyncTask like this:
protected void doInBackground(String... params) {
URL url = new URL(yourTextUrl);
try {
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setConnectTimeout(MyConstants.CONNECTION_TIMEOUT);
connection.setReadTimeout(MyConstants.READ_TIMEOUT);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.connect();
Writer writer = new OutputStreamWriter(connection.getOutputStream());
String out = params[0];
Log.d("Uploading this: ", out);
writer.write(out);
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
Log.e("ERR", e.getMessage());
if (null != e.getMessage() && e.getMessage().equals("timeout")) {
this.cancel(true);
}
} finally {
connection.disconnect();
}
}
connection is either HttpURLConnection or HttpsURLConnection, based on
your protocol.
I hope it's clear enough.
Related
I'm having trouble with loading an image from a URL into my Android app using the Google Places API.
I got the part with the API working and I can see the image if I type the URL in my browser. The code fails in the below line:
Bitmap myBitmap = BitmapFactory.decodeStream(input);
The strange thing is, it simply jumps to the return null in the catch clause without executing the println commands.
I should also explain that I'm using two URL's since the first URL in the google API is a redirect page.
I assume that the problem is that the final page that's being loaded isn't actually a "real" image (I mean it looks like
https://lh4.googleusercontent.com/XXX/s1600-w400/
rather than something like
http://something/image.jpg)
Below is the entire method I'm using:
public Bitmap getImageData(Place p) {
try {
String src= "https://maps.googleapis.com/maps/api/place/photo?maxwidth=400&photoreference="+
p.getPhoto_reference()+
"&key="+
this.context.getResources().getString(places_api);
Log.d("srcsrc", src);
URL url = new URL(src);
HttpsURLConnection ucon = (HttpsURLConnection) url.openConnection();
ucon.setInstanceFollowRedirects(false);
URL secondURL = new URL(ucon.getHeaderField("Location"));
HttpsURLConnection connection = (HttpsURLConnection) secondURL.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
}
catch (Exception e)
{
e.printStackTrace();
System.out.println("Bitmap exception" + e);
return null;
}
}
Appreciate your help.
use Picasso like this :
Picasso.with(context).load(src).into(imageView );
It will do the following:
Handling ImageView recycling and download cancelation in an adapter.
Complex image transformations with minimal memory use.
Automatic memory and disk caching.
I'm getting mad about HttpUrlConnection an Outputstreams.
I just want to send a string to php and from there put it in a database.
The last two nights I read nearly thousand guides and threads about sending data to webserver, tried almost everything I read - and it's still not working.
protected void phpPOST(final String ServerURL, final String StringToPost)
{
Thread newthread = new Thread() {
public void run() {
//1. set URL and connect to server
HttpURLConnection connection = null;
try {
URL server = new URL(ServerURL + "teilnehmer_update.php");
connection = (HttpURLConnection) server.openConnection();
//2. set method to POST and enable output
connection.setRequestMethod("POST");
connection.setDoOutput(true);
//3. open outputstream and send string to url
OutputStreamWriter outstream = new OutputStreamWriter(connection.getOutputStream());
outstream.write(StringToPost);
outstream.flush();
outstream.close();
} catch (Exception e) {
e.printStackTrace();
Log.i("Error!", "ERROR is " + e);}
finally {if (connection != null) {connection.disconnect();}}
}
};
newthread.start();
}
I reduced my php-file to very simple, to secure it's not a php problem. Tried from browser, works fine.
<?php
// for testing, should create an empty file when no no data is recieved.
$file = fopen('test.txt', 'w');
$id = $_POST['id'];
fwrite($file, $id);
fclose($file);
?>
I don't get any errors - so, I don't know what to fix. LogCat is also empty.
I think the Problem is something with the Outputstream (also tried versions BufferdOS,OS,DataOS). As far as I get it, the connection is should open when I create the OS and write to it. - But, in my case it does not do anything...
Any ideas what's wrong with the code ?
Thanks
There is a string variable and an image photo taken from the camera intent. The directory location of the photo is known. I want to make a HTTP post of the string variable and the image photo to a webserver at the same time. Is that possible ? If so , how to do it ?
From what I understand, you need to send an image and a string to your webserver within a single POST request. Here's how you'd proceed.
You first need to Base64 encode your image.
Start by converting your image into a byte array:
InputStream image = new FileInputStream(<path_to_image>);
byte[] buff = new byte[8192];
int readBytes;
ByteArrayOutputStream byteArrOS = new ByteArrayOutputStream();
try {
while ( (readBytes = inputStream.read(buff) ) != -1) {
byteArrOS.write(buff, 0, readBytes);
}
} catch (IOException e) {
e.printStackTrace();
}
byte[] b = byteArrOS.toByteArray();
Then convert it to Base64:
String bsfEncodedImage = Base64.encodeToString(b, Base64.DEFAULT);
Then build a query with the the string and the resulting Base64 both encoded with URLEncoder and "utf-8":
strImgQuery = "str="+URLEncoder.encode(<string_data>, "utf-8")+"&image="+URLEncoder.encode(bsfEncodedImage, "utf-8");
Declare a new URL:
URL postUrl = new URL("http://<IP>/postreq");
Open the connection:
HttpURLConnection conn = (HttpURLConnection)postUrl.openConnection();
Set output to "true" (needed for a POST request but not for GET):
conn.setDoOutput(true);
Set the request method to POST:
conn.setRequestMethod("POST");
The timeout:
conn.setReadTimeout(1e4);
Buffer the output to the output stream and flush/run:
Writer buffWriter = new OutputStreamWriter(conn.getOutputStream());
buffWrite.write(strImgQuery);
buffWriter.flush();
buffWriter.close();
At server side you'll get the str and image POST params which is dependent on your server implementation.
Note that your url must follow the URL Specification, otherwise you'll get a MalformedURLException. If that's the case, be sure to check what exactly the issue is. For example if you use a non-existing ttp "protocol" instead of http your exception will look something like this:
java.net.MalformedURLException: unknown protocol: ttp
at java.net.URL.<init>(URL.java:592)
at java.net.URL.<init>(URL.java:482)
at java.net.URL.<init>(URL.java:431)
at com.pheromix.core.lang.NumberFormatExceptionExample.MalformedURLExceptionExample.sendGetRequest(MalformedURLExceptionExample.java:28)
at com.pheromix.core.lang.NumberFormatExceptionExample.MalformedURLExceptionExample.main(MalformedURLExceptionExample.java:17)
Also, this is a synchronous operation and is ran on the UI thread. It might be costly or it might not depending on other operations you're already running and the size of the POST data. If the problem arises, run the job on another thread.
You can use URLEncoder
String strUrl = "http://192.168.1.9/impots/" +URLEncoder.encode("outil.php?action=OutilImporterDonneesMobile", "utf-8");
URL url = new URL(strUrl);
I'm using the following code to grab images from the web. It uses Gridview and depending on position, picks a URL from an array. It works but the loading of images is often hit or miss. Almost every time I start the app, a different number of images load.
It also has issues when changing from portrait to landscape view, 5 out of 10 images may be displayed then I'll turn the device and usually lose all the images. Sometimes a few do show up though.
Any ideas on making this more robust?
try {
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
return bm;
} catch (IOException e) {
Log.d("DEBUGTAG", "error...");
}
return null;
One thing I read is that there's a known bug with decoding Bitmaps from an InputStream, and the suggested fix from Google was to use a FlushedInputStream (example in below URL):
http://android-developers.blogspot.com/2010/07/multithreading-for-performance.html
Also, I'd put the download code into an AsyncTask. Here's what I currently use for mine:
public static Bitmap loadImageFromUri(URI uri)
{
URL url;
try {
url = uri.toURL();
} catch (MalformedURLException e) {
Log.v("URL Exception", "MalformedURLException");
return null;
}
try
{
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
return BitmapFactory.decodeStream(new FlushedInputStream(input));
}
catch (IOException e)
{
e.printStackTrace();
return null;
}
}
I just pass in a URI due to the way I've got the rest of my code set up, you could pass in a URL instead and skip the first part. This will keep the download from tying up your UI thread.
Given a Url for an image, I want to downoload it and paste it onto my canvas in android. How do I retrieve the image into my app ?
Please help.
Thanks,
de costo.
Dont forget to give the app the permission to connect to the Web,
in the AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
You can use the following code to download an image:
URLConnection connection = uri.toURL().openConnection();
connection.connect();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, 8 * 1024);
Bitmap bmp = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
Requires the following permission in AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
There is a an HTTP client library that might be supported in Android now, but for any fine grain control you can use URL & HttpURLConnection. the code will look something like this:
URL connectURL = new URL(<your URL goes here>);
HttpURLConnection conn = (HttpURLConnection)connectURL.openConnection();
// do some setup
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("GET");
// connect and flush the request out
conn.connect();
conn.getOutputStream().flush();
// now fetch the results
String response = getResponse(conn);
where getResponse() looks something like this, in your case you are getting
a pile of binary data back you might want to change the StringBuffer to a byte array
and chunk the reads by a larger increment.
private String getResponseOrig(HttpURLConnection conn)
{
InputStream is = null;
try
{
is = conn.getInputStream();
// scoop up the reply from the server
int ch;
StringBuffer sb = new StringBuffer();
while( ( ch = is.read() ) != -1 ) {
sb.append( (char)ch );
}
return sb.toString();
}
catch(Exception e)
{
Log.e(TAG, "biffed it getting HTTPResponse");
}
finally
{
try {
if (is != null)
is.close();
} catch (Exception e) {}
}
return "";
}
As you are talking about image data which can be large, other things you need to be assiduous about in Android is making sure you release your memory as soon as you can, you've only got 16mb of heap to play with for all apps and it runs out fast and the GC will drive you nuts if you aren't really good about giving back memory resources