7

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

此代码正在打开 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
    );
}

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

4

1 回答 1

9

我做了一些研究,并用 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);
    }

}


}

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

于 2013-09-09T21:06:24.527 回答