12.简单实现一个android相机拍照,相册选图加剪裁效果,用SharedPreferences 库保存,每次进来都有,还有一个图片加水印的效果

public class MainActivity extends AppCompatActivity {

    public static final int NONE = 0;
    public static final int PHOTOHRAPH = 1;// 拍照
    public static final int PHOTOZOOM = 2; // 缩放
    public static final int PHOTORESOULT = 3;// 结果

    public static final String IMAGE_UNSPECIFIED = "image/*";
    Button button0 = null;
    Button button1 = null;
    private Button mQuXiao;
    private CircleImageView imageView;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
    }






    private void initView() {
        imageView = (CircleImageView) findViewById(R.id.imageID);

      
SharedPreferences spf = getSharedPreferences("testSP", 0);
// 第一步:取出字符串形式的Bitmap
String image = spf.getString("image", "");
// 第二步:利用Base64将字符串转换为ByteArrayInputStream
byte[] byteArray = Base64.decode(image, Base64.DEFAULT);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
        byteArray);
// 第三步:利用ByteArrayInputStream生成Bitmap
Bitmap bitmap = BitmapFactory.decodeStream(byteArrayInputStream);
//设置图片到imageview
imageView.setImageBitmap(bitmap);



        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                View inflate = LayoutInflater.from(MainActivity.this).inflate(R.layout.pop, null);
                final PopupWindow window = new PopupWindow(inflate, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
                button0 = inflate.findViewById(R.id.btn_01);
                button1 = inflate.findViewById(R.id.btn_02);
                mQuXiao = inflate.findViewById(R.id.mQuXiao);


                mQuXiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        window.dismiss();
                    }
                });

                button0.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_PICK, null);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
                        startActivityForResult(intent, PHOTOZOOM);
                        window.dismiss();
                    }
                });

                button1.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(Environment.getExternalStorageDirectory(), "temp.jpg")));
                        startActivityForResult(intent, PHOTOHRAPH);
                    }
                });
                window.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#63B8FF")));
                window.setOutsideTouchable(true);
                window.setFocusable(true);
                window.showAtLocation(inflate, Gravity.BOTTOM, 0, 0);
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == NONE)
            return;
        // 拍照
        if (requestCode == PHOTOHRAPH) {
            //设置文件保存路径这里放在跟目录下
            File picture = new File(Environment.getExternalStorageDirectory() + "/temp.jpg");
            startPhotoZoom(Uri.fromFile(picture));
        }

        if (data == null)
            return;

        // 读取相册缩放图片
        if (requestCode == PHOTOZOOM) {
            startPhotoZoom(data.getData());
        }
        // 处理结果
        if (requestCode == PHOTORESOULT) {
            Bundle extras = data.getExtras();
            if (extras != null) {
               
Bitmap photo = extras.getParcelable("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0 - 100)压缩文件
//下面这两行是加入图片水印的,如果不想要,直接imageView.setImageBitmap(photo);就可以了
Bitmap bitmap = addTimeFlag(photo);
imageView.setImageBitmap(bitmap);
//---------------------------------下面的是将Bitmap转换成字符串保存至SharedPreferences

byte[] byteArray = stream.toByteArray();
String image = new String(Base64.encodeToString(byteArray, Base64.DEFAULT));
SharedPreferences spf = getSharedPreferences("testSP", 0);
SharedPreferences.Editor editor = spf.edit();
editor.putString("image", image);
editor.commit();
//-----------------------------------
               
            }

        }

        super.onActivityResult(requestCode, resultCode, data);
    }


    public void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 100);
        intent.putExtra("outputY", 100);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTORESOULT);
    }

  
//图片水印
    private Bitmap addTimeFlag(Bitmap src){
        // 获取原始图片与水印图片的宽与高
        int w = src.getWidth();
        int h = src.getHeight();
        Bitmap newBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas mCanvas = new Canvas(newBitmap);
        // 往位图中开始画入src原始图片
        mCanvas.drawBitmap(src, 0, 0, null);
        //添加文字
        Paint textPaint = new Paint();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String time = sdf.format(new Date(System.currentTimeMillis()));
        textPaint.setColor(Color.RED) ;
        textPaint.setTextSize(10);
        String familyName = "宋体";
//        Typeface typeface = Typeface.create(familyName,
//                Typeface.BOLD_ITALIC);
//        textPaint.setTypeface(typeface);
//        textPaint.setTextAlign(Align.CENTER);

        mCanvas.drawText(time, (float)(w*1)/7, (float)(h*14)/15, textPaint);
        mCanvas.save();
        mCanvas.restore();
        return newBitmap ;
    }

}

//下面介绍一下那个将Bitmap转换成字符串保存至SharedPreferences,并取出来的方法。

//------------------------------------1,将Bitmap转换成字符串保存至SharedPreferences------------------

      //得到要保存的图片

        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),

                R.drawable.as);

        // 第一步:将Bitmap压缩至字节数组输出流ByteArrayOutputStream

        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        bitmap.compress(CompressFormat.PNG, 80, byteArrayOutputStream);

        // 第二步:利用Base64将字节数组输出流中的数据转换成字符串String

        byte[] byteArray = byteArrayOutputStream.toByteArray();

        String image = new String(Base64.encodeToString(byteArray,

                Base64.DEFAULT));

        // 第三步:将String保持至SharedPreferences

     SharedPreferences spf = getSharedPreferences("testSP", MODE_APPEND);

        Editor editor = spf.edit();

        editor.putString("image", image);

        editor.commit();

//------------------------------------------2.从SharedPreferences中取出Bitmap,显示在ImageView中

  SharedPreferences spf = getSharedPreferences("testSP", MODE_APPEND);

        // 第一步:取出字符串形式的Bitmap

        String image = spf.getString("image", "");

        // 第二步:利用Base64将字符串转换为ByteArrayInputStream

        byte[] byteArray = Base64.decode(image, Base64.DEFAULT);

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(

                byteArray);

        // 第三步:利用ByteArrayInputStream生成Bitmap

        Bitmap bitmap = BitmapFactory.decodeStream(byteArrayInputStream);

        //设置图片到imageview

        mImageView.setImageBitmap(bitmap);

猜你喜欢

转载自blog.csdn.net/weixin_42061754/article/details/81230953