zoukankan      html  css  js  c++  java
  • 自定义一个带框框的相机

    废话不多说先上效果图 点击红框内 可以获取 坐标点 像素点

    我先把主界面的代码复制上来

      1 package com.ltfz.photo.photovalue.activity;
      2 
      3 import android.content.Intent;
      4 import android.graphics.Bitmap;
      5 import android.graphics.BitmapFactory;
      6 import android.graphics.Color;
      7 import android.graphics.ImageFormat;
      8 import android.graphics.Rect;
      9 import android.graphics.YuvImage;
     10 import android.hardware.Camera;
     11 import android.os.AsyncTask;
     12 import android.os.Bundle;
     13 import android.os.Handler;
     14 import android.os.Message;
     15 import android.support.v7.app.AppCompatActivity;
     16 import android.util.Log;
     17 import android.view.MotionEvent;
     18 import android.view.SurfaceHolder;
     19 import android.view.SurfaceView;
     20 import android.view.View;
     21 import android.widget.Button;
     22 import android.widget.ImageButton;
     23 import android.widget.ImageView;
     24 import android.widget.TextView;
     25 
     26 import com.ltfz.photo.photovalue.CustView.DrawRectView;
     27 import com.ltfz.photo.photovalue.CustView.ViewFinderView;
     28 import com.ltfz.photo.photovalue.R;
     29 import com.ltfz.photo.photovalue.Utils.ImageDispose;
     30 import com.ltfz.photo.photovalue.Utils.SDPathUtils;
     31 
     32 import java.io.BufferedOutputStream;
     33 import java.io.ByteArrayOutputStream;
     34 import java.io.File;
     35 import java.io.FileOutputStream;
     36 import java.io.IOException;
     37 import java.text.SimpleDateFormat;
     38 import java.util.Calendar;
     39 import java.util.Locale;
     40 import java.util.TimeZone;
     41 
     42 public class Camera1Activity extends AppCompatActivity implements SurfaceHolder.Callback {
     43 
     44     //指明需要使用到相机
     45     //声明相机 因为需要用到自定义相机
     46     private Camera         camera;
     47     //使用屏幕surface
     48     //只要是自定义的相机视频动画等需要用到屏幕view
     49     private SurfaceView    surfaceView;
     50     //屏幕管理者
     51     private SurfaceHolder  surfaceHolder;
     52     //屏幕管理的方法名
     53     private ImageButton    imageButton2;
     54     private ImageView      imageView3;
     55     private Button         btnpz;
     56     private SurfaceView    surfaceView1;
     57     private SurfaceHolder  mHolder;
     58     private Bitmap         photo;
     59     private Bitmap         bit_photo;
     60     private ViewFinderView viewFinderView;
     61     private TextView       tv_rgb;
     62     private DrawRectView   mDrawIV;
     63     private int            width;
     64     private int            height;
     65     private ImageView      iv;
     66     private Bitmap         bitmap;
     67     //    private KuangkuangView rectOnCamera;
     68 
     69     @Override
     70     protected void onCreate(Bundle savedInstanceState) {
     71         super.onCreate(savedInstanceState);
     72         setContentView(R.layout.activity_camera1);
     73         btnpz = (Button) findViewById(R.id.btn_pz);
     74         tv_rgb = (TextView) findViewById(R.id.tv_rgb);
     75         surfaceView1 = (SurfaceView) findViewById(R.id.surfaceView2);
     76         viewFinderView = (ViewFinderView) findViewById(R.id.viewfinder);
     77         mDrawIV = (DrawRectView) findViewById(R.id.draw_view);
     78         iv = (ImageView) findViewById(R.id.iv_image);
     79         //        getIntent().getIntExtra("hei");
     80         width = getIntent().getExtras().getInt("width");
     81         height = getIntent().getExtras().getInt("hei");
     82         //        rectOnCamera = (KuangkuangView) findViewById(R.id.rectOnCamera);
     83 
     84         btnpz.setOnClickListener(new View.OnClickListener() {
     85             @Override
     86             public void onClick(View view) {
     87                 capture(view);
     88             }
     89         });
     90         surfaceView1.setOnClickListener(new View.OnClickListener() {
     91             @Override
     92             public void onClick(View view) {
     93                 try {
     94                     camera.autoFocus(null);//点击屏幕自动对焦
     95                 } catch (Exception e) {
     96                     e.printStackTrace();
     97                     setStartPreView(camera, mHolder);
     98                 }
     99 
    100 
    101 
    102             }
    103         });
    104         camera = getCamera();
    105         mHolder = surfaceView1.getHolder();
    106         mHolder.addCallback(this);
    107 
    108         setStartPreView(camera, mHolder);
    109         camera.setPreviewCallback(new Camera.PreviewCallback() {
    110             @Override
    111             public void onPreviewFrame(byte[] bytes, Camera camera) {
    112                 //                BitmapFactory.Options options = new BitmapFactory.Options();
    113                 //                options.inTempStorage = new byte[100 * 1024];
    114                 //                options.inPreferredConfig = Bitmap.Config.RGB_565;
    115                 //                options.inPurgeable = true;
    116                 //                options.inSampleSize = 12;
    117                 //                options.inInputShareable = true;
    118                 //                photo = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
    119 
    120                 Camera.Size size = camera.getParameters().getPreviewSize();
    121                 try {
    122                     YuvImage image = new YuvImage(bytes, ImageFormat.NV21, size.width, size.height, null);
    123                     if (image != null) {
    124                         ByteArrayOutputStream stream = new ByteArrayOutputStream();
    125                         image.compressToJpeg(new Rect(0, 0, size.width, size.height), 80, stream);
    126 
    127                         photo = BitmapFactory.decodeByteArray(stream.toByteArray(), 0, stream.size());
    128                         Log.e("Sys12", "Error12:" + photo);
    129                         //**********************
    130                         //因为图片会放生旋转,因此要对图片进行旋转到和手机在一个方向上
    131                         //                        rotateMyBitmap(bmp);
    132                         //**********************************
    133 
    134                         stream.close();
    135                     }
    136                 } catch (Exception ex) {
    137                     Log.e("Sys", "Error:" + ex.getMessage());
    138                 }
    139 
    140 
    141             }
    142         });
    143 
    144         surfaceView1.setOnTouchListener(new View.OnTouchListener() {
    145             @Override
    146             public boolean onTouch(View view, MotionEvent event) {
    147                 try {
    148                     int x = (int) event.getX();
    149 
    150                     int y = (int) event.getY();
    151                     if (x < width / 2 || y < height / 2 || x > width / 2 * 3 || y > height) {
    152                         return false;
    153                     }
    154 
    155 
    156                     if (event.getAction() == MotionEvent.ACTION_UP) {
    157                         int color = photo.getPixel(x, y);
    158                         // 如果你想做的更细致的话 可以把颜色值的R G B 拿到做响应的处理
    159                         int r = Color.red(color);
    160                         int g = Color.green(color);
    161                         int b = Color.blue(color);
    162                         int a = Color.alpha(color);
    163                         Log.i("123", "r=" + r + ",g=" + g + ",b=" + b);
    164                         tv_rgb.setText("a=" + a + ",r=" + r + ",g=" + g + ",b="
    165                                 + b + ",x=" + x + ",y=" + y);
    166                         tv_rgb.setTextColor(Color.rgb(r, g, b));
    167                         //                    tv_se.setBackgroundColor(Color.rgb(r, g, b));
    168                     } else if (event.getAction() == MotionEvent.ACTION_MOVE) {
    169                         int color = photo.getPixel(x, y);
    170                         // 如果你想做的更细致的话 可以把颜色值的R G B 拿到做响应的处理
    171                         int r = Color.red(color);
    172                         int g = Color.green(color);
    173                         int b = Color.blue(color);
    174                         int a = Color.alpha(color);
    175                         Log.i("123", "r=" + r + ",g=" + g + ",b=" + b);
    176                         tv_rgb.setText("a=" + a + ",r=" + r + ",g=" + g + ",b="
    177                                 + b + ",x=" + x + ",y=" + y);
    178                         tv_rgb.setTextColor(Color.rgb(r, g, b));
    179                         //                    tv_se.setBackgroundColor(Color.rgb(r, g, b));
    180                     } else if (event.getAction() == MotionEvent.ACTION_DOWN) {
    181                         int color = photo.getPixel(x, y);
    182                         // 如果你想做的更细致的话 可以把颜色值的R G B 拿到做响应的处理
    183                         int r = Color.red(color);
    184                         int g = Color.green(color);
    185                         int b = Color.blue(color);
    186                         int a = Color.alpha(color);
    187                         Log.i("123", "r=" + r + ",g=" + g + ",b=" + b);
    188                         tv_rgb.setText("a=" + a + ",r=" + r + ",g=" + g + ",b="
    189                                 + b + ",x=" + x + ",y=" + y);
    190                         tv_rgb.setTextColor(Color.rgb(r, g, b));
    191                         //                    tv_se.setBackgroundColor(Color.rgb(r, g, b));
    192                     }
    193                 } catch (Exception e) {
    194                     e.printStackTrace();
    195                 }
    196 
    197                 return false;
    198             }
    199         });
    200         //        rectOnCamera.setIIAutoFocus((KuangkuangView.IAutoFocus) this);
    201         //定义DisplayMetrics 对象;
    202         //        DisplayMetrics dm = new DisplayMetrics();
    203         //        //取得窗口属性
    204         //        getWindowManager().getDefaultDisplay().getMetrics(dm);
    205         //        //窗口的宽度
    206         //        int screenWidth = dm.widthPixels;
    207         //        //窗口高度
    208         //        int screenHeight = dm.heightPixels;
    209         //
    210         //        //获取屏幕的百分之八的比例宽度(宽和高是根据业务需求可以自己自行设定的)
    211         //        width = (int) (screenWidth * 0.5);
    212         //        //获取屏幕的百分之7的比例高度
    213         //        height = (int) (screenHeight * 0.5);
    214         mDrawIV.setMaskSize(width, height);
    215         //        capture()
    216 
    217     }
    218 
    219 
    220     @Override
    221     protected void onPause() {
    222         super.onPause();
    223         releaseCamera();
    224     }
    225 
    226     private void releaseCamera() {
    227         if (camera != null) {
    228             camera.setPreviewCallback(null);
    229             camera.stopPreview();
    230             camera.release();
    231             camera = null;
    232         }
    233     }
    234 
    235 
    236     @Override
    237     protected void onResume() {
    238         super.onResume();
    239         if (camera == null) {
    240             camera = getCamera();
    241             if (mHolder != null) {
    242                 setStartPreView(camera, mHolder);
    243             }
    244         }
    245     }
    246 
    247     private Camera getCamera() {
    248         Camera camera;
    249         try {
    250             camera = Camera.open();
    251         } catch (Exception e) {
    252             camera = null;
    253         }
    254 
    255         return camera;
    256     }
    257 
    258     private void setStartPreView(Camera camera, SurfaceHolder holder) {
    259         try {
    260             //把camera捕获到的图像显示在SurfaceView里
    261             camera.setPreviewDisplay(holder);
    262             //将预览效果横屏转为竖直的camera
    263             camera.setDisplayOrientation(90);
    264             camera.startPreview();
    265         } catch (IOException e) {
    266             e.printStackTrace();
    267         }
    268     }
    269 
    270     @Override
    271     public void surfaceCreated(SurfaceHolder surfaceHolder) {
    272         //开始预览
    273 
    274         setStartPreView(camera, mHolder);
    275     }
    276 
    277     @Override
    278     public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {
    279         // 当改变时候,先停止预览
    280         camera.stopPreview();
    281         //再次开始预览
    282         setStartPreView(camera, mHolder);
    283     }
    284 
    285     @Override
    286     public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
    287         // 释放掉相机
    288         releaseCamera();
    289     }
    290 
    291     public void capture(View view) {
    292 
    293         Camera.Parameters parameters = camera.getParameters();
    294 
    295         parameters.setPictureFormat(ImageFormat.JPEG);
    296         // 设定预览尺寸
    297         parameters.setPreviewSize(900, 300);
    298         // 对焦模式 自动
    299         parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO);
    300         // 自动对焦的回调
    301         camera.autoFocus(new Camera.AutoFocusCallback() {
    302             @Override
    303             public void onAutoFocus(boolean success, Camera camera) {
    304                 if (success) {
    305                     // 自动对焦成功后,拍照,会走mPictureCallback回调
    306                     camera.takePicture(null, null, mPictureCallback);
    307                 }
    308             }
    309         });
    310     }
    311 
    312     private Camera.PictureCallback mPictureCallback = new Camera.PictureCallback() {
    313         @Override
    314         public void onPictureTaken(byte[] data, Camera camera) {
    315 
    316             new saveTask().execute(data);
    317             //            String mFilePath = Environment.getExternalStorageDirectory().getPath();
    318             //            mFilePath = mFilePath + "/" + "temp.png";
    319             //            File tempFile = new File(mFilePath);
    320             //
    321             //            try {
    322             //                // 拿着byte[] data,写入图片文件
    323             //                FileOutputStream fos = new FileOutputStream(tempFile);
    324             //                fos.write(data);
    325             //                fos.close();
    326             //
    327             //                // 我们将打开新的activity,把图片地址传递给下一个activity
    328             //                Intent intent = new Intent(Camera1Activity.this, ResultActivity.class);
    329             //                intent.putExtra("picPatch", tempFile.getAbsolutePath());
    330             //                startActivity(intent);
    331             //
    332             //                finish();
    333             //            } catch (FileNotFoundException e) {
    334             //                e.printStackTrace();
    335             //            } catch (IOException e) {
    336             //                e.printStackTrace();
    337             //            }
    338         }
    339     };
    340 
    341 
    342     class saveTask extends AsyncTask<byte[], Void, Boolean> {
    343         @Override
    344         protected Boolean doInBackground(byte[]... params) {
    345             byte[] photoData = params[0];
    346             savePicture(photoData);
    347             return null;
    348         }
    349     }
    350 
    351     Handler handler = new Handler() {
    352         @Override
    353         public void handleMessage(Message msg) {
    354             super.handleMessage(msg);
    355             iv.setImageBitmap(bitmap);
    356         }
    357     };
    358 
    359     private void savePicture(byte[] photoData) {
    360         BitmapFactory.Options options = new BitmapFactory.Options();
    361         options.inTempStorage = new byte[100 * 1024];
    362         options.inPreferredConfig = Bitmap.Config.RGB_565;
    363         options.inPurgeable = true;
    364         options.inSampleSize = 12;
    365         options.inInputShareable = true;
    366         photo = BitmapFactory.decodeByteArray(photoData, 0, photoData.length, options);
    367         //        if (isqian) {
    368 
    369         photo = ImageDispose.rotaingImageView(90, photo);
    370         int pheight = photo.getHeight();
    371         int pwidth = photo.getWidth();
    372         float vh = (float) pheight / ((float) height * 2);
    373         float vw = (float) pwidth / ((float) width * 2);
    374         System.out.println(" " + width + ", height:" + height + ",vw " + vw + " , vh:" + vh + ",pheight"+pheight  +", pwidth"+pwidth);
    375         bitmap = Bitmap.createBitmap(photo, (int) (width * 2 * vw / 4), (int) (height * 2 * vh / 4), (int) (width * 2 * vw / 2), (int) (height * 2 * vh) / 4);
    376         handler.sendEmptyMessage(0);
    377 
    378         //        } else {
    379         //            photo = ImageDispose.rotaingImageView(270, photo);
    380         //        }
    381         //        Matrix matrix = new Matrix();
    382         //        matrix.preRotate(90);
    383         //        photo = Bitmap.createBitmap(photo, 0, 0, photo.getWidth(), photo.getHeight(), matrix, true);
    384         //        Message msg = Message.obtain();
    385         //        msg.what = UPDTEPREVIEW;
    386         //        Bundle bundle = new Bundle();
    387         //        bundle.putByteArray(UPDATEBITMAP, photoData);
    388         //        msg.setData(bundle);
    389         //        takeHandler.sendEmptyMessage(UPDTE_PREVIEW);
    390         Calendar calendar = Calendar.getInstance(TimeZone.getDefault());
    391         SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HH-mm-ss-SSS", Locale.getDefault());
    392         String pictureName = format.format(calendar.getTime());
    393         // 存入系统相册
    394         //        currentPath = MediaStore.Images.Media.insertImage(getContentResolver(), photo, pictureName, "来自迈步手环");
    395         //        LocalDataSaveTool.getInstance(TakePhotoActivity.this).writeSp(MyConfingInfo.PICTURE_NAME, luj);
    396         //        String filePath = MyConfingInfo.getSdcardPath()
    397         //                + File.separator + "Pictures" + File.separator + pictureName + ".jpg";
    398         // 存入系统相册
    399         String filePathRoot = SDPathUtils.getSdcardPath() +
    400                 File.separator + "DCIM" +
    401                 File.separator + "Camera" +
    402                 File.separator;
    403         //        SimpleDateFormat timeStampFormat = new SimpleDateFormat(
    404         //                "yyyy_MM_dd_HH_mm_ss");
    405         //        String filename = timeStampFormat.format(new Date());
    406         //        ContentValues values = new ContentValues();
    407         //        values.put(MediaStore.Audio.Media.TITLE, filename);
    408         //
    409         //        photoUri = getContentResolver().insert(
    410         //                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
    411         //
    412         File root = new File(filePathRoot);
    413         if (!root.exists()) {
    414             root.mkdirs();
    415         }
    416         String filePath = filePathRoot + pictureName + ".jpg";
    417         File file = new File(filePath);
    418         if (!file.exists()) {
    419             try {
    420                 file.createNewFile();
    421             } catch (IOException e) {
    422                 e.printStackTrace();
    423             }
    424         }
    425         FileOutputStream fileOutputStream = null;
    426         BufferedOutputStream outputStream = null;
    427         try {
    428             fileOutputStream = new FileOutputStream(file);
    429             outputStream = new BufferedOutputStream(fileOutputStream);
    430             outputStream.write(photoData);
    431         } catch (IOException e) {
    432             e.printStackTrace();
    433             try {
    434                 if (fileOutputStream != null) {
    435                     outputStream.flush();
    436                     fileOutputStream.flush();
    437                 }
    438                 if (fileOutputStream != null) {
    439                     fileOutputStream.close();
    440                     outputStream.close();
    441                 }
    442             } catch (IOException es) {
    443                 es.printStackTrace();
    444             }
    445         } finally {
    446             try {
    447                 if (fileOutputStream != null) {
    448                     fileOutputStream.flush();
    449                     if (outputStream != null) {
    450                         outputStream.flush();
    451                     }
    452                 }
    453                 if (fileOutputStream != null) {
    454                     fileOutputStream.close();
    455                     if (outputStream != null) {
    456                         outputStream.close();
    457                     }
    458                 }
    459             } catch (IOException e) {
    460                 e.printStackTrace();
    461             }
    462             //            currentPath = filePath;
    463         }
    464         Intent scanIntent;
    465         Log.i("paizjap", "照片扫描路径:" + filePath);
    466 
    467         File scanFile = new File(filePath);
    468         // 我们将打开新的activity,把图片地址传递给下一个activity
    469         //        Intent intent = new Intent(Camera1Activity.this, ResultActivity.class);
    470         //        intent.putExtra("picPatch",filePath);
    471         //        startActivity(intent);
    472         //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
    473         //            scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.fromFile(scanFile));
    474         //        } else {
    475         //            scanIntent = new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.fromFile(scanFile));
    476         //        }
    477         //        sendBroadcast(scanIntent);
    478 
    479 
    480     }
    481 
    482 }

    自定义相机  自动对焦我就不多说了啊 网上一搜一大堆哈!
    在页面的布局上:使用

    在FrameLayout内部
    使用surfaceView来当作相机的画面
    这时候我们就可以自定义一个DrawRectView边框 在布局中直接调用
    DrawRectView
    package com.ltfz.photo.photovalue.CustView;
    
    import android.content.Context;
    import android.graphics.Canvas;
    import android.graphics.Color;
    import android.graphics.Paint;
    import android.util.AttributeSet;
    import android.widget.ImageView;
    
    /**
     * Created by love on 2019/10/14.
     */
    
    public class DrawRectView  extends ImageView{
    
            private int width;
            private int height;
            private int maskWidth;
            private int maskHeight;
            private Paint linePaint;
    
    
        public DrawRectView(Context context, int width){
            super(context);
            init();
        }
    
        public DrawRectView(Context context, AttributeSet attrs) {
            super(context, attrs);
            init();
        }
    
        public DrawRectView(Context context, AttributeSet attrs, int defStyleAttr, int width){
            super(context, attrs, defStyleAttr);
            init();
        }
    
        private void init() {
    
            linePaint = new Paint();
            linePaint.setAntiAlias(true);
            linePaint.setColor(Color.RED);
            linePaint.setStyle(Paint.Style.FILL);
            linePaint.setStrokeWidth(8f);
        }
    
    
        @Override
        protected void onDraw(Canvas canvas) {
            super.onDraw(canvas);
    
            int h = Math.abs((height - maskHeight) / 2);
            int w = Math.abs((width - maskWidth) / 2);
            //        Log.i("myLog","w "+ w+" h " +h);
    
    //        //画矩形框的四个角
    //        //左上角
    //        canvas.drawLine(w, h, w + 30, h, linePaint);// _
    //        canvas.drawLine(w, h, w, h + 30, linePaint);// |
    //        //左下角
    //        canvas.drawLine(w, h + maskHeight, w, h + maskHeight - 30, linePaint);// |
    //        canvas.drawLine(w, h + maskHeight, w + 30, h + maskHeight, linePaint);// _
    //        //右上角
    //        canvas.drawLine(w + maskWidth, h, w + maskWidth - 30, h, linePaint);// _
    //        canvas.drawLine(w + maskWidth, h, w + maskWidth, h + 30, linePaint);// |
    //        //右下角
    //        canvas.drawLine(w + maskWidth, h + maskHeight, w + maskWidth, h + maskHeight - 30, linePaint);// |
    //        canvas.drawLine(w + maskWidth, h + maskHeight, w + maskWidth - 30, h + maskHeight, linePaint);// _
            // 画矩形框的四个角
            //左上角
            canvas.drawLine(w, h, w + maskWidth, h, linePaint);// _
            canvas.drawLine(w, h, w, h + maskHeight/2, linePaint);// |
            //左下角
            canvas.drawLine(w, h + maskHeight/2, w, h , linePaint);// |
            canvas.drawLine(w, h + maskHeight/2, w+maskWidth , h + maskHeight/2, linePaint);// _
            //右上角
            canvas.drawLine(w + maskWidth, h, w, h, linePaint);// _
            canvas.drawLine(w + maskWidth, h, w + maskWidth, h + maskHeight/2, linePaint);// |
            //右下角
            canvas.drawLine(w + maskWidth, h + maskHeight/2, w + maskWidth, h, linePaint);// |
            canvas.drawLine(w + maskWidth, h + maskHeight/2, w , h + maskHeight/2, linePaint);// _
        }
    
    
        public void PixSize(Integer w, Integer h) {
            width = w;
            height = h;
        }
    
        public void setMaskSize(Integer widths, Integer heights) {
            maskWidth = widths;
            maskHeight = heights;
        }
    
        public int[] getMaskSize() {
            return new MaskSize().size;
        }
    
        private class MaskSize {
            private final int[] size;
    
            private MaskSize() {
                this.size = new int[]{maskWidth, maskHeight, width, height};
            }
        }
    
    
    }
    

      


    有啥不懂的可以下方留言解惑!











  • 相关阅读:
    关于《注意力模型--Attention注意力机制》的学习
    神经网络参数计算
    FPN(feature pyramid networks)算法讲解
    RetinaNet-focal loss
    论文阅读: RetinaNet
    CNN+LSTM:看图说话
    非极大值抑制-NMS
    python IO文件操作 file文件操作
    软件测试定义 分类
    软件生命周期
  • 原文地址:https://www.cnblogs.com/rocksmall/p/11683996.html
Copyright © 2011-2022 走看看