Source Code for Upload Image in Android
While learning Android, most of the developers find it difficult to upload an Image to Server from Android App using PHP Webservice as server-side. Sometimes you exercise nothing wrong in Android Code just Image doesn't upload to the server. Sometimes you practise not follow the same method to receive Image on the server equally android application sending method.
There are several ways to upload Image or whatever other file from Android to Server using PHP Webservice. I'm going to upload the paradigm in base64 encoded grade. I'll share the source code for both Android and PHP.
Web Service will as well save the image on the server after receiving it.
How Does It Work?
- Select the Prototype from Phone Gallary
- Encode the Image to Base64
- Send the Paradigm as Postal service Parameter using PHP Webservice
- Webservice volition receive encoded prototype
- Decode Epitome and save it on the Server
Source Lawmaking
Android:
At present information technology'due south fourth dimension to practise some Android coding for uploading the image. In this app, for uploading the prototype nosotros're using Retrofit. For to add the Retrofit in Android app add together the dependencies in your app. Below are the dependencies.
implementation 'com.squareup.retrofit2:retrofit:2.3.0' implementation 'com.squareup.retrofit2:converter-gson:ii.3.0' implementation 'com.squareup.okhttp3:logging-interceptor:three.9.0'
Before starting the Android app coding I wanna show you the demo of the app.
Now you run across the demo correct, let's offset making the app by designing its UI. Below is the activity_main.xml file.
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ImageView android:id="@+id/imageView" android:layout_width="match_parent" android:layout_height="200dp" android:contentDescription="@null" android:scaleType="centerCrop" /> <LinearLayout style="?android:attr/buttonBarStyle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:orientation="horizontal" android:weightSum="2"> <Button android:id="@+id/selectImageButton" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_marginEnd="10dp" android:layout_weight="1" android:text="@string/select_image" tools:ignore="ButtonStyle" /> <Push android:id="@+id/uploadImageButton" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:text="@string/select_image" tools:ignore="ButtonStyle" /> </LinearLayout> </RelativeLayout>
In our MainActivity when the user clicks on the selectImagepush it will open the Gallery app and let y'all select the image. Below is the code for when a user presses the select prototype button.
findViewById<Button>(R.id.selectImageButton).setOnClickListener { val intent = Intent( Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI) startActivityForResult(Intent.createChooser(intent, "Select Moving picture"), PICK_IMAGE_REQUEST_CODE) } Now when the user selects the image from the Galleryapp the result will come up in the onActivityResultmethod. Below is the MainActivity onActivityResultmethod.
override fun onActivityResult(requestCode: Int, resultCode: Int, information: Intent?) { super.onActivityResult(requestCode, resultCode, information) if (requestCode == PICK_IMAGE_REQUEST_CODE && RESULT_OK == resultCode) { data?.permit { try { bitmap = uiHelper.decodeUri(this, information technology.data) imageView.setImageBitmap(bitmap) } catch (east: Exception) { if (bitmap != null) imageView.setImageBitmap(bitmap) } } } } After the user selects an prototype the onActivityResultmethod volition exist called. So, we store the image every bit Bitmap in our global bitmapobject. Before proceeding next you guys see that nosotros're decoding the image with a decodeUrimethod to get the resulted bitmap.Below is the decodeUrimethod.
@Throws(FileNotFoundException::grade) fun decodeUri(context: Context, selectedImage: Uri): Bitmap { val o = BitmapFactory.Options() o.inJustDecodeBounds = true BitmapFactory.decodeStream(context.contentResolver.openInputStream(selectedImage), zilch, o) val REQUIRED_SIZE = 140 var width_tmp = o.outWidth var height_tmp = o.outHeight var scale = 1 while (true) { if (width_tmp / ii < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) { intermission } width_tmp /= 2 height_tmp /= two calibration *= 2 } val o2 = BitmapFactory.Options() o2.inSampleSize = scale return BitmapFactory.decodeStream(context.contentResolver.openInputStream(selectedImage), null, o2) } So, nosotros select the image and store the resulted prototype in the bitmapobject. Now nosotros merely need to upload the prototype the user press the Upload Prototype button.
findViewById<Button>(R.id.uploadImageButton).setOnClickListener { if (bitmap != nix) { val imageBytes = uiHelper.getImageBytes(bitmap!!) uploadImage(imageBytes) } else Toast.makeText(this, "No image selected", Toast.LENGTH_SHORT).prove() } To upload the epitome offset nosotros check if a user selects the image earlier or not. Second, we demand to catechumen the bitmap into Base64 ByteArray and third upload the prototype bytes to the server. Below is thegetImageBytes method.
fun getImageUrl(bitmap: Bitmap): String { val byteArrayOutputStream = ByteArrayOutputStream() bitmap.shrink(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream) val bytes = byteArrayOutputStream.toByteArray() return Base64.encodeToString(bytes, Base64.DEFAULT) } The prep work is done. Now information technology's time to upload the paradigm bytes to the server. Below is the uploadImagemethod code.
individual fun uploadImage(imageBytes: String) { ServiceApi.Factory.getInstance(this).uploadImage(imageBytes) .enqueue(object : Callback<StatusMessageResponse> { override fun onFailure(call: Phone call<StatusMessageResponse>?, t: Throwable?) { Toast.makeText(MainActivity.this,"Epitome uploaded",Toast.LENGTH_SHORT).testify() // Prototype uploaded successfully } override fun onResponse(telephone call: Call<StatusMessageResponse>?, response: Response<StatusMessageResponse>?) { // Mistake Occurred during uploading } }) } The ServerApiis the instance of a Retrofit interface. Below is the ServerApiclass.
interface ServiceApi { companion object { private const val BASE_URL = "" // Base url of your hosting } @FormUrlEncoded @POST("") // end_point url fun uploadImage(@Field("image_bytes") imageBytes: String): Call<StatusMessageResponse> class Mill { companion object { private var service: ServiceApi? = goose egg fun getInstance(context: Context): ServiceApi? { if (service == null) { val builder = OkHttpClient().newBuilder() builder.readTimeout(xv, TimeUnit.SECONDS) builder.connectTimeout(15, TimeUnit.SECONDS) builder.writeTimeout(15, TimeUnit.SECONDS) if (BuildConfig.DEBUG) { val interceptor = HttpLoggingInterceptor() interceptor.level = HttpLoggingInterceptor.Level.Body builder.addInterceptor(interceptor) } val file = File(context.cacheDir, "cache_dir") if (!file.exists()) file.mkdirs() val cacheSize: Long = 10 * 1024 * 1024 // x MiB val cache = okhttp3.Cache(file, cacheSize) builder.cache(cache) val retrofit: Retrofit retrofit = Retrofit.Builder() .client(builder.build()) .addConverterFactory(GsonConverterFactory.create()) .baseUrl(BASE_URL) .build() service = retrofit.create(ServiceApi::grade.java) return service } else { return service } } } } } In this article, I'm non gonna prove yous how the Retrofit works and how to create its instance. Yous can acquire virtually Retrofit from this article. Each telephone call created from ServerApitin can exist synchronous or asynchronous HTTP asking to the remote web server.
Note:There are ii things that you need to practice. Offset, you need to add your web serverBASE_URL.Second, add together the end-signal URL to POSTannotation. And in the end, don't forget to add the Net permission in the Manifest file.
Alright, our code for Android Appis complete. You can become the complete source code of the in a higher place app from GitHub.
Download Complete Code
PHP:
// receive image as POST Parameter $image = str_replace('information:image/png;base64,', '', $_POST['prototype']); $image = str_replace(' ', '+', $paradigm); // Decode the Base64 encoded Image $data = base64_decode($paradigm); // Create Image path with Image name and Extension $file = '../images/' . "MyImage" . '.jpg'; // Salvage Image in the Paradigm Directory $success = file_put_contents($file, $data); Disclosure of Material Connection: Some of the links in the mail higher up are "affiliate links." This means if yous click on the link and purchase the particular, we will receive an affiliate commission. Regardless, we but recommend products or services nosotros use personally and believe will add value to our readers.
Source: https://codinginfinite.com/android-image-upload-example-php-source-code/
0 Response to "Source Code for Upload Image in Android"
Enregistrer un commentaire