I m using a Webview for a nice page and i need to upload images. Now the Problem, most Images on phones are 2-3MB and i need to resize the image and lower quality before upload starts. So how could i resize it with the sample code found on stackoverflow ?
This code is opening the Filechooser :
//Android 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("image/*");
startActivityForResult(
Intent.createChooser(i, "Image Browser"),
FILECHOOSER_RESULTCODE
);
}
Now i need some resize and make a copy and upload the resized. (I know howto create a resized copy, but not how i could interact with the above code)
i did some research and create a solution with the content on SO..
It would directly open gallery from filechooser html and resize the image to sample size of 200x200 and quality 75.
package it.meininserat;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Locale;
import it.meininserat.R;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.text.TextPaint;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewConfiguration;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;
import android.widget.Toast;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@SuppressLint({ "NewApi", "SetJavaScriptEnabled" })
public class MainActivity extends Activity {
// Main PAGE URL !!
String myUrl = "http://www.imagebanana.com/"; // http://www.meininserat.it/mobile";
boolean hasNavigationBar = false;
AdView adView;
WebView mWebView;
Context context;
ProgressDialog progDailog;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// loader
progDailog = ProgressDialog.show(this, "Verbindung aufbauen..",
"Lade ....bitte warten....", true);
// Fullscreen and Menubar in ICS
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
hasNavigationBar = !ViewConfiguration.get(this)
.hasPermanentMenuKey();
if (hasNavigationBar == true) {
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
getActionBar().show();
} else {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
getActionBar().hide();
}
} else {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
// check internet
if (isNetworkAvailable(context) != true) {
progDailog.dismiss();
Toast.makeText(getApplicationContext(),
"Fehler ! Keine Internetverbindung.", Toast.LENGTH_LONG)
.show();
finish();
}
// load url
mWebView = (WebView) findViewById(R.id.webview);
mWebView.setWebViewClient(new HelloWebViewClient());
mWebView.getSettings().setJavaScriptEnabled(true);
mWebView.getSettings().setPluginState(PluginState.ON);
mWebView.getSettings().setPluginsEnabled(true);
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setUserAgentString(
Locale.getDefault().getLanguage());
/*
* Language detection URL String myDisplayLang =
* Locale.getDefault().getDisplayLanguage() .toString();
*
* if (myDisplayLang.contentEquals("italiano")) { myUrl =
* "http://www.meininserat.it/mobile"; }else{ myUrl =
* "http://www.meininserat.it/mobile"; }
*/
mWebView.loadUrl(myUrl);
mWebView.setWebChromeClient(new CustomWebChromeClient());
mWebView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
progDailog.dismiss();
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
progDailog.dismiss();
Toast.makeText(getApplicationContext(),
"Fehler ! " + description, Toast.LENGTH_LONG).show();
}
});
}
// check internet connection
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager
.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_rate:
new AppRating().goToMarket(context);
return true;
case R.id.menu_exit:
finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (mWebView.canGoBack() == true) {
mWebView.goBack();
} else {
finish();
}
return true;
}
return super.onKeyDown(keyCode, event);
}
private class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor
.getColumnIndex(MediaStore.MediaColumns._ID));
Uri baseUri = Uri.parse("content://media/external/images/media");
return Uri.withAppendedPath(baseUri, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
// Fix Upload
private ValueCallback<Uri> mUploadMessage;
private final static int FILECHOOSER_RESULTCODE = 1;
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
if (requestCode == FILECHOOSER_RESULTCODE) {
if (null == mUploadMessage)
return;
if (resultCode != RESULT_OK) {
mUploadMessage.onReceiveValue(null);
return;
}
Uri result = intent.getData(); // get file
if (result == null) {
mUploadMessage.onReceiveValue(null);
return;
}
String fPath = getPath(result);
// we actually don't allow http links in gallery like google+ or
// facebook images
File file = new File(fPath);
if (!file.exists()) {
mUploadMessage.onReceiveValue(null);
Toast.makeText(getApplicationContext(),
"Please select a local Imagefile.", Toast.LENGTH_LONG)
.show();
return;
}
// Resize+
Bitmap bitmap = BitmapFactory.decodeFile(fPath);
int newWidth = 200;
int newHeight = 200;
Bitmap scaledBitmap = Bitmap.createBitmap(newWidth, newHeight,
Config.ARGB_8888);
float ratioX = newWidth / (float) bitmap.getWidth();
float ratioY = newHeight / (float) bitmap.getHeight();
float middleX = newWidth / 2.0f;
float middleY = newHeight / 2.0f;
Matrix scaleMatrix = new Matrix();
scaleMatrix.setScale(ratioX, ratioY, middleX, middleY);
Canvas canvas = new Canvas(scaledBitmap);
canvas.setMatrix(scaleMatrix);
canvas.drawBitmap(bitmap, middleX - bitmap.getWidth() / 2, middleY
- bitmap.getHeight() / 2, new Paint(
Paint.FILTER_BITMAP_FLAG));
String resizedFileName = "ImageResized.png";
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File(sdCard.getAbsolutePath());
File filedir = new File(dir, resizedFileName);
try {
FileOutputStream fos = new FileOutputStream(filedir);
scaledBitmap.compress(CompressFormat.PNG, 70, fos);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mUploadMessage.onReceiveValue(null);
return;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mUploadMessage.onReceiveValue(null);
return;
}
mUploadMessage.onReceiveValue(getImageContentUri(context, filedir));
}
}
protected class CustomWebChromeClient extends WebChromeClient {
// For Android > 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType, String capture) {
openFileChooser(uploadMsg);
}
// Andorid 3.0 +
public void openFileChooser(ValueCallback<Uri> uploadMsg,
String acceptType) {
openFileChooser(uploadMsg);
}
// Android 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
mUploadMessage = uploadMsg;
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
// i.addCategory(Intent.CATEGORY_APP_GALLERY);
i.setType("image/*");
// startActivityForResult( Intent.createChooser(i,
// "Image Browser"),FILECHOOSER_RESULTCODE);
startActivityForResult(i, FILECHOOSER_RESULTCODE);
}
}
}
Hope it could help someone...
来源:https://stackoverflow.com/questions/18667881/android-customwebchromeclient-openfilechooser-resize-image-before-upload