为了账号安全,请及时绑定邮箱和手机立即绑定

图像处理(拍照,导入,旋转,裁剪,),裁剪是可自由改变宽高比例。

标签:
Java Android

我这个是在学习过程中写的代码,可能性能和界面不够好,但是能正常运行,也可以看效果。所以在这里保存代码的同时给大家分享一下。参考了不少网站,其中CSDN博客的比较多,也有开源代码库等。毕竟初学者就参看很多代码,把自己想要的取出来或者理解后按照自己的需求更改。

我还是比较喜欢少说,毕竟新手说多了容易误导别人,所以直接给代码,注释挺多的。也有一些不用的代码,但是以后工作中拿出来使用,所以一起保存到这里。

裁剪的时候事直接下载一个别人的库,在这里:https://github.com/jdamcd/android-crop

然后把这个库导入到自己项目中,(在下载的项目 Properties--Android--Is Library,然后在自己项目中Properties--Android--add,选择刚才的自己添加的库)

最后在ActivityManife.xml 中配置一下就可以在自己项目中调用刚才库的需要的方法。

疑问:
有一个问题,在改变图片RGB时,如果Bitmap 对象是drawable里面的图片可以正常调RGB的效果,但是导入进来的或者拍照过来的图片就不行了,我是打算导入的图片或者拍照的图片先在ImageView里面显示,然后给这个图片调RGB颜色,或者先裁剪一部分在ImageView里显示再调RGB颜色,这个我不太会,有高手能帮我就更好了。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

import com.soundcloud.android.crop.Crop;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

private Button jiequ_Button;// 新建的按钮
private Button paizhao_Button;// 拍照的按钮
private Button daoru_Button;// 导入的按钮
private Button xuanzhuan_Button;// 旋转的按钮
private Button rgba_Button;// RGBA的按钮

private SeekBar r_SeekBar;
private SeekBar g_SeekBar;
private SeekBar b_SeekBar;
private SeekBar a_SeekBar;

private TextView r_TextView;
private TextView g_TextView;
private TextView b_TextView;
private TextView a_TextView;

private ImageView iv_image; // 图片窗口
private int Take_Photo = 0; // 拍照
private int Daoru = 1; // 导入
private int JieQu = 2;
private File appDir; // 文件夹

private File file; // 源文件文件
private File filecrop; // 截取文件文件
private Uri imageuri; // 原照片的uri
private Uri imagecropuri; // 截取照片的uri
private Uri imagedaoru; // 导入的图片的uri

private boolean paizhao = false;
private boolean daoru = false;
private boolean jiequ = false;

private Matrix matrix = new Matrix();

int progress = 0;// 旋转角度初始化
private Canvas canvas;
private Paint paint;
private Bitmap baseBitmap;
private Bitmap afterBitmap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    jiequ_Button = (Button) findViewById(R.id.jiequ);
    paizhao_Button = (Button) findViewById(R.id.paizhao);
    daoru_Button = (Button) findViewById(R.id.daoru);
    xuanzhuan_Button = (Button) findViewById(R.id.xuanzhuan);
    iv_image = (ImageView) findViewById(R.id.imageView1);

    rgba_Button = (Button) findViewById(R.id.rgb);
    r_SeekBar = (SeekBar) findViewById(R.id.rs);
    g_SeekBar = (SeekBar) findViewById(R.id.gs);
    b_SeekBar = (SeekBar) findViewById(R.id.bs);
    a_SeekBar = (SeekBar) findViewById(R.id.as);

    r_SeekBar.setOnSeekBarChangeListener(seekBarChange);
    g_SeekBar.setOnSeekBarChangeListener(seekBarChange);
    b_SeekBar.setOnSeekBarChangeListener(seekBarChange);
    a_SeekBar.setOnSeekBarChangeListener(seekBarChange);

    /**
     * 下面为RGBA的代码
     */
    // 从资源文件中获取图片

     baseBitmap = BitmapFactory.decodeResource(getResources(),
             R.drawable.ic_launcher);
    /* iv_image.setDrawingCacheEnabled(true);
     baseBitmap=Bitmap.createBitmap(iv_image.getDrawingCache());;
      iv_image.setDrawingCacheEnabled(false);*/
    /*if (daoru) {
        try {
            baseBitmap = MediaStore.Images.Media.getBitmap(
                    this.getContentResolver(), imagedaoru);
        } catch (FileNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }*/

        // 获取一个与baseBitmap大小一致的可编辑的空图片
        afterBitmap = Bitmap.createBitmap(baseBitmap.getWidth(),
                baseBitmap.getHeight(), baseBitmap.getConfig());
        canvas = new Canvas(afterBitmap);
        paint = new Paint();
    //}

        /**
         * RGBA 的代码在这里结束
         */

    r_TextView = (TextView) findViewById(R.id.r);
    g_TextView = (TextView) findViewById(R.id.g);
    b_TextView = (TextView) findViewById(R.id.b);
    a_TextView = (TextView) findViewById(R.id.a);

    // 先验证手机是否有sdcard
    String status = Environment.getExternalStorageState();
    if (status.equals(Environment.MEDIA_MOUNTED)) {
        appDir = new File(Environment.getExternalStorageDirectory(), "Amu");
        if (!appDir.exists()) {
            appDir.mkdir();
        }

        file = new File(appDir, System.currentTimeMillis() + ".jpg");
        imageuri = Uri.fromFile(file);

        filecrop = new File(appDir, "amu" + System.currentTimeMillis()
                + ".jpg");
        imagecropuri = Uri.fromFile(filecrop);
    }

    jiequ_Button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            r_SeekBar.setVisibility(View.INVISIBLE);
            g_SeekBar.setVisibility(View.INVISIBLE);
            b_SeekBar.setVisibility(View.INVISIBLE);
            a_SeekBar.setVisibility(View.INVISIBLE);

            r_TextView.setVisibility(View.INVISIBLE);
            g_TextView.setVisibility(View.INVISIBLE);
            b_TextView.setVisibility(View.INVISIBLE);
            a_TextView.setVisibility(View.INVISIBLE);

            jiequ = true;

            Toast.makeText(getApplicationContext(), "截取按钮点击了",
                    Toast.LENGTH_LONG).show();
            if (paizhao) {
                daoru=false;
                /*cropImg(imageuri);*/
                beginCrop(imageuri);
            }

            if (daoru) {
                paizhao=false;

                /*cropImg(imagedaoru);*/
                beginCrop(imagedaoru);

            }

        }
    });

    paizhao_Button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) { // 图片名称 时间命名

            r_SeekBar.setVisibility(View.INVISIBLE);
            g_SeekBar.setVisibility(View.INVISIBLE);
            b_SeekBar.setVisibility(View.INVISIBLE);
            a_SeekBar.setVisibility(View.INVISIBLE);

            r_TextView.setVisibility(View.INVISIBLE);
            g_TextView.setVisibility(View.INVISIBLE);
            b_TextView.setVisibility(View.INVISIBLE);
            a_TextView.setVisibility(View.INVISIBLE);

            paizhao = true;
            daoru=false;
            jiequ=false;

            takePhoto();
        }

    });

    daoru_Button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            r_SeekBar.setVisibility(View.INVISIBLE);
            g_SeekBar.setVisibility(View.INVISIBLE);
            b_SeekBar.setVisibility(View.INVISIBLE);
            a_SeekBar.setVisibility(View.INVISIBLE);

            r_TextView.setVisibility(View.INVISIBLE);
            g_TextView.setVisibility(View.INVISIBLE);
            b_TextView.setVisibility(View.INVISIBLE);
            a_TextView.setVisibility(View.INVISIBLE);

            daoru = true;
            paizhao=false;
            jiequ=false;
            DaoruPhoto();
        }
    });

    xuanzhuan_Button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {

            r_SeekBar.setVisibility(View.INVISIBLE);
            g_SeekBar.setVisibility(View.INVISIBLE);
            b_SeekBar.setVisibility(View.INVISIBLE);
            a_SeekBar.setVisibility(View.INVISIBLE);

            r_TextView.setVisibility(View.INVISIBLE);
            g_TextView.setVisibility(View.INVISIBLE);
            b_TextView.setVisibility(View.INVISIBLE);
            a_TextView.setVisibility(View.INVISIBLE);

            progress = progress + 90;
            // TODO Auto-generated method stub

            /* 如果是拍照的 */
            if (paizhao) {
                try {
                    XuanZhuan(imageuri, iv_image, progress);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            /* 如果是导入的 */
            if (daoru) {
                try {
                    XuanZhuan(imagedaoru, iv_image, progress);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            /* 如果是截取的 */
            if (jiequ) {
                try {
                    XuanZhuan(imagecropuri, iv_image, progress);
                } catch (FileNotFoundException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
        }
    });

    rgba_Button.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            r_SeekBar.setVisibility(View.VISIBLE);
            g_SeekBar.setVisibility(View.VISIBLE);
            b_SeekBar.setVisibility(View.VISIBLE);
            a_SeekBar.setVisibility(View.VISIBLE);

            r_TextView.setVisibility(View.VISIBLE);
            g_TextView.setVisibility(View.VISIBLE);
            b_TextView.setVisibility(View.VISIBLE);
            a_TextView.setVisibility(View.VISIBLE);

        }
    });
}

/**
 * 下面为RGBA的代码
 */
private SeekBar.OnSeekBarChangeListener seekBarChange = new OnSeekBarChangeListener() {

    @Override
    public void onStopTrackingTouch(SeekBar arg0) {
        // TODO Auto-generated method stub
        // 获取每个SeekBar当前的值
        float progressR = r_SeekBar.getProgress() / 128f;
        float progressG = g_SeekBar.getProgress() / 128f;
        float progressB = b_SeekBar.getProgress() / 128f;
        float progressA = a_SeekBar.getProgress() / 128f;

        // 根据SeekBar定义RGBA的矩阵
        float[] src = new float[] { progressR, 0, 0, 0, 0, 0, progressG, 0,
                0, 0, 0, 0, progressB, 0, 0, 0, 0, 0, progressA, 0 };
        // 定义ColorMatrix,并指定RGBA矩阵
        ColorMatrix colorMatrix = new ColorMatrix();
        colorMatrix.set(src);
        // 设置Paint的颜色
        paint.setColorFilter(new ColorMatrixColorFilter(src));
        // 通过指定了RGBA矩阵的Paint把原图画到空白图片上
        canvas.drawBitmap(baseBitmap, new Matrix(), paint);
        iv_image.setImageBitmap(afterBitmap);

        /**
         * RGBA的代码结束
         */
    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
        // TODO Auto-generated method stub

    }
};

private void handleCrop(int resultCode, Intent result) {
    if (resultCode == Activity.RESULT_OK) {
        System.out.println(" handleCrop: Crop.getOutput(result) "+Crop.getOutput(result));
        iv_image.setImageURI( Crop.getOutput(result));

// mCircleView.setImageBitmap( getCircleBitmap(Crop.getOutput(result)));
} else if (resultCode == Crop.RESULT_ERROR) {
// Toast.makeText(getActivity(), Crop.getError(result).getMessage(),
// Toast.LENGTH_SHORT).show();
}
}

/*String.valueOf( System.currentTimeMillis()*/

 private void beginCrop(Uri source) {
        boolean isCircleCrop = false;
        String fileName = "Temp_" + "amu"+".png";
        File cropFile = new File( appDir, fileName);
        Uri outputUri = Uri.fromFile( cropFile);

        /**
         * 这里就是用到下载的库
         */
        new Crop( source).output( outputUri).setCropType( isCircleCrop).start( this);

        Toast.makeText(getApplicationContext(), "我运行了", Toast.LENGTH_LONG).show();
    }

/**
 * 拍照的方法
 */
private void takePhoto() {
    // TODO Auto-generated method stub

    Intent intent = new Intent(
            android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imageuri);
    startActivityForResult(intent, Take_Photo);
}

/**
 * 导入图片的方法
 */
private void DaoruPhoto() {
    Toast.makeText(getApplicationContext(), "导入按钮点击了", Toast.LENGTH_LONG)
            .show();
    Intent intent = new Intent(Intent.ACTION_PICK);
    intent.setType("image/*");// 相片类型
    startActivityForResult(intent, Daoru);
}

/**
 * 截取的方法
 * 
 * @param uri
 *            图片路径
 */
/*public void cropImg(Uri uri) {
    Intent intent = new Intent("com.android.camera.action.CROP");
    intent.setDataAndType(uri, "image/*");
    intent.putExtra("crop", "true"); // 设置裁剪
    intent.putExtra("aspectX", 2);// aspectX aspectY 是宽高的比例
    intent.putExtra("aspectY", 1);
    intent.putExtra("outputX", 700);// outputX outputY 是裁剪图片宽高
    intent.putExtra("outputY", 700);
    intent.putExtra("return-data", false);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, imagecropuri);
    intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
    intent.putExtra("noFaceDetection", true);
    startActivityForResult(intent, JieQu);
}

*/
/**

  • 旋转图片的方法
  • @param uri
  • 图片的uri
  • @param imageView
  • 要显示的位置
  • @param progress
  • 角度
  • @throws FileNotFoundException
  • @throws IOException
    */

    public void XuanZhuan(Uri uri, ImageView imageView, int progress)
    throws FileNotFoundException, IOException {

    // 读取uri所在的图片
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(
            this.getContentResolver(), uri);
    // 设置旋转角度
    matrix.setRotate(progress);
    // 重新绘制Bitmap
    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(),
            bitmap.getHeight(), matrix, true);
    imageView.setImageBitmap(bitmap);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == Activity.RESULT_OK) {

        switch (requestCode) {
        case 0: // 拍照
    
            FileInputStream fis = null;
            try {
    
                fis = new FileInputStream(file);
                Bitmap bit = BitmapFactory.decodeStream(fis);
                iv_image.setImageBitmap(bit);
            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } finally {
                try {
                    fis.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
    
            /************ 下面的代码的得到的是缩略图的代码 ****/
            /*
             * Bundle bundle = data.getExtras(); Bitmap bitmap = (Bitmap)
             * bundle.get("data");// 获取相机返回的数据,并转换为Bitmap图片格式
             * 
             * saveImage(bitmap); //saveTOSD(bitmap);
             * 
             * ((ImageView)
             * findViewById(R.id.imageView1)).setImageBitmap(bitmap);
             */
    
            break;
    
        case 6709:
    
            handleCrop( resultCode, data);
            /*Bundle extras = data.getExtras();
            if (extras != null) {
                try {
                    Bitmap bitmap = BitmapFactory
                            .decodeStream(getContentResolver()
                                    .openInputStream(imagecropuri));
                    iv_image.setImageBitmap(bitmap);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }*/
    
            break;
    
        case 1: // 导入图片
            imagedaoru = data.getData();
            String image_path = imagedaoru.getPath(); // 图片路径
            ContentResolver cr = this.getContentResolver();
            try {
                Bitmap bitmap1 = BitmapFactory.decodeStream(cr
                        .openInputStream(imagedaoru));
                iv_image.setImageBitmap(bitmap1);
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
            break;
    
        default:
            Toast.makeText(this, "出现错误操作", Toast.LENGTH_SHORT).show();
    
            break;
        }
    }

    }

    /**/
    /**** 下面的代码为保存文件的代码 /
    /
    可以以后使用 */
    /***
    /

    /
    //**

  • 保存图片的另一种方式
  • @param bitmap
    /
    /
  • private void saveTOSD(Bitmap bitmap) { // TODO Auto-generated method stub
  • String sdStatus = Environment.getExternalStorageState(); if
  • (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
  • Log.i("TestFile", "SD card is not avaiable/writeable right now.");
  • return; }
  • String name = new
  • DateFormat().format("yyyyMMdd_hhmmss",Calendar.getInstance(Locale.CHINA)
  • )+ ".jpg"; FileOutputStream b = null;
  • File file = new File("/sdcard/myImage/"); file.mkdirs();// 创建文件夹 String
  • fileName = "/sdcard/myImage/"+name;
  • try { b = new FileOutputStream(fileName);
  • bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件 } catch
  • (FileNotFoundException e) { e.printStackTrace(); } finally { try {
  • b.flush(); b.close(); } catch (IOException e) { e.printStackTrace(); } }
  • }
    *//**
  • 保存图片到本地的方法
  • @param bitmap
    /
    /
  • public static void saveImage(Bitmap bmp) { File appDir = new
  • File(Environment.getExternalStorageDirectory(), "Amu"); if
  • (!appDir.exists()) { appDir.mkdir(); } String fileName =
  • System.currentTimeMillis() + ".jpg"; File file = new File(appDir,
  • fileName); try { FileOutputStream fos = new FileOutputStream(file);
  • bmp.compress(CompressFormat.JPEG, 100, fos); fos.flush(); fos.close(); }
  • catch (FileNotFoundException e) { e.printStackTrace(); } catch
  • (IOException e) { e.printStackTrace(); } }
    */

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }

}

点击查看更多内容
7人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消