gpt4 book ai didi

Android CustomWebChromeClient openFileChooser 在上传前调整图像大小

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:25:34 25 4
gpt4 key购买 nike

我正在为一个漂亮的页面使用 Webview,我需要上传图片。现在的问题是,手机上的大多数图片都是 2-3MB,我需要调整图片大小并在上传开始前降低质量。那么我如何使用在 stackoverflow 上找到的示例代码调整它的大小?

此代码打开文件选择器:

//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
);
}

现在我需要调整大小并制作副本并上传调整大小的文件。(我知道如何创建调整大小的副本,但不知道如何与上面的代码交互)

最佳答案

我做了一些研究并使用 SO 上的内容创建了一个解决方案..

它将直接从 filechooser html 打开图库并将图像调整为样本大小 200x200 和质量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);
}

}


}

希望它可以帮助某人...

关于Android CustomWebChromeClient openFileChooser 在上传前调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18667881/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com