I have to make an android application, in which user can browse image from gallery or from camera.. the image is then conerted to string and then uploaded to the local server. At the server the image is converted again and stored as an image. Ihave compressed the image but i am unable to upload it please help me
Below is the code..
package com.example.hdfcuploadapp;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import android.util.Base64;
import android.app.Activity;``
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
public class MainActivity extends Activity {
private static final int REQ_CODE_PICK_IMAGE = 1;
private static final int CAMERA_REQUEST = 1888;
private static View popupView = null;
private static PopupWindow popupWindow = null;
private static Button buttonBrowse = null;
private static String compressedImage = null;
private static Point position = null;
private static Bitmap imageSelected = null;
private static String selectedImageRealPath = null;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonUpload = (Button) findViewById(R.id.buttonUpload);
buttonUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
buttonBrowse = (Button) findViewById(R.id.buttonBrowse);
buttonBrowse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(position!= null){
showPopup(MainActivity.this, position);
}
}
@SuppressWarnings("deprecation")
private void showPopup(final Activity activity, Point position) {
int popupWidth = 120;
int popupHeight = 130;
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater) activity.getSystemService(LAYOUT_INFLATER_SERVICE);
popupView = layoutInflater.inflate(R.layout.popup, linearLayout);
popupWindow = new PopupWindow(activity);
popupWindow.setContentView(popupView);
popupWindow.setWidth(popupWidth);
popupWindow.setHeight(popupHeight);
int offset_X = 85;
int offset_Y = 5;
popupWindow.setBackgroundDrawable(new BitmapDrawable());
popupWindow.showAtLocation(popupView, Gravity.NO_GRAVITY, position.x + offset_X, position.y + offset_Y);
}
});
}
@Override
public void onWindowFocusChanged(boolean hasFocus){
int[] location = new int[2];
buttonBrowse.getLocationOnScreen(location);
position = new Point();
position.x = location[0];
position.y = location[1];
}
public void buttonGallery_Click(View v){
Intent intent = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, REQ_CODE_PICK_IMAGE);
}
public void buttonTakePhoto_Click(View v){
popupWindow.dismiss();
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent){
switch(requestCode) {
case REQ_CODE_PICK_IMAGE:
if(resultCode == RESULT_OK){
Uri selectedImageUri = intent.getData();
selectedImageRealPath = getRealPathFromURI(selectedImageUri);
imageSelected = BitmapFactory.decodeFile(selectedImageRealPath);
compressedImage = imageCompression(selectedImageRealPath);
final ImageView imageViewPhoto = (ImageView) findViewById(R.id.imageViewPhoto);
imageViewPhoto.setImageBitmap(imageSelected);
}
break;
case CAMERA_REQUEST:
if(resultCode == RESULT_OK){
Uri selectedImageUri = intent.getData();
selectedImageRealPath = getRealPathFromURI(selectedImageUri);
imageSelected = (Bitmap) intent.getExtras().get("data");
MediaStore.Images.Media.insertImage(getContentResolver(), imageSelected, String.valueOf(System.currentTimeMillis()), "This is an Image.");
compressedImage = imageCompression(selectedImageRealPath);
final ImageView imageViewPhoto = (ImageView) findViewById(R.id.imageViewPhoto);
imageViewPhoto.setImageBitmap(imageSelected);
}
break;
}
popupWindow.dismiss();
}
private String imageCompression(String filePath) {
File imageFile = new File(filePath);
FileInputStream fis = null;
try
{
fis = new FileInputStream(imageFile);
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, baos );
byte[] b = baos.toByteArray();
return Base64.encodeToString(b, Base64.DEFAULT);
}
public String getRealPathFromURI(Uri contentUri)
{
try
{
String[] proj = {MediaStore.Images.Media.DATA};
@SuppressWarnings("deprecation")
Cursor cursor = managedQuery(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
catch (Exception e)
{
return contentUri.getPath();
}
}
}
public String EncodeToString(Bitmap image)
{
Bitmap immagex=image;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
immagex.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] b = baos.toByteArray();
String imageEncoded = Base64.encodeToString(b,Base64.DEFAULT);
return imageEncoded;
}
make sure that while passing the bitmap to this method try to reduce the size of bitmap as much as possible and if possible run in background thread
Image ivcard = Base64ToImage(vcard);
//Image thumb = image.GetThumbnailImage(120, 120, ()=>false, IntPtr.Zero);
// thumb.Save(Path.ChangeExtension(fileName, "thumb"));
try
{
string x = System.DateTime.Now.Hour.ToString() + System.DateTime.Now.Minute.ToString() + System.DateTime.Now.Second.ToString() + System.DateTime.Now.Millisecond.ToString();
string ipath1;
ipath1 = "ma\\imagesc1" + x + ".jpg";
ivcard.Save(Server.MapPath(ipath1), System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch { }
private Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
using (MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length))
{
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
}
public void uploadImage(String filePath) {
File imgFile=new File(filePath);
RequestParams requestParamsForUploadImage=new RequestParams();
requestParamsForUploadImage.put("file",imgFile);
AsyncHttpClient client = new AsyncHttpClient();
client.post("URL of server upload file",
requestParamsForUploadImage, new JsonHttpResponseHandler() {
// response code '200'
@Override
public void onSuccess(int statusCode, org.apache.http.Header[] headers, org.json.JSONObject response) {
//Image is uploaded successfully...
}
// When the response returned by REST has Http
// response code other than '200' such as '404',
// '500' or '403' etc
@Override
public void onFailure(int statusCode, org.apache.http.Header[] headers, java.lang.Throwable throwable, org.json.JSONObject errorResponse) {
//Failed to upload
}
});
}
As I have used AsyncHttpClient library to perform file upload.Don't forget to add it in your project
Compress image to 75% then upload.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 75, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.