安卓小案例收集四(多媒体)

原创 2016年05月30日 22:58:06

加载大图片

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


  public void click(View v){
    Options opts = new Options();
    //只请求图片宽高,不解析图片像素
    opts.inJustDecodeBounds = true;
    //返回null,获取图片宽高,保存在opts对象中
    BitmapFactory.decodeFile("sdcard/dog.jpg", opts);
    //获取图片宽高
    int imageWidth = opts.outWidth;
    int imageHeight = opts.outHeight;

    //获取屏幕宽高
    Display dp = getWindowManager().getDefaultDisplay();
int screenWidth = dp.getWidth();
    int screenHeight = dp.getHeight();

    //计算缩放比例
    int scale = 1;
    int scaleWidth = imageWidth / screenWidth;
    int scaleHeight = imageHeight / screenHeight;

    //判断取哪个比例
    if(scaleWidth >= scaleHeight && scaleWidth > 1){
        scale = scaleWidth;
    }
    else if(scaleWidth < scaleHeight && scaleHeight > 1){
        scale = scaleHeight;
    }

    //设置缩小比例
    opts.inSampleSize = scale;
    opts.inJustDecodeBounds = false;
    //获取缩小后的图片的像素信息
    Bitmap bm = BitmapFactory.decodeFile("sdcard/dog.jpg", opts);

    ImageView iv = (ImageView) findViewById(R.id.iv);
    iv.setImageBitmap(bm);

  }

创建图片副本

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

    //加载原图
    Bitmap bmSrc = BitmapFactory.decodeResource(getResources(), R.drawable.photo3);

    //创建副本
    //1.创建与原图一模一样大小的bitmap对象,该对象中目前是没有内容的,可以比喻为创建了和原图一样大小的白纸
    Bitmap bmCopy = Bitmap.createBitmap(bmSrc.getWidth(), bmSrc.getHeight(), bmSrc.getConfig());
    //2.创建画笔对象
    Paint paint = new Paint();
    //3.创建画板,把白纸铺到画板上
    Canvas canvas = new Canvas(bmCopy);
    //4.开始作画
    canvas.drawBitmap(bmSrc, new Matrix(), paint);

    ImageView iv_src = (ImageView) findViewById(R.id.iv_src);
    iv_src.setImageBitmap(bmSrc);
    ImageView iv_copy = (ImageView) findViewById(R.id.iv_copy);
    iv_copy.setImageBitmap(bmCopy);
}

简单图片特效

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //加载原图
    Bitmap bmSrc = BitmapFactory.decodeResource(getResources(), R.drawable.photo3);

    //创建副本
    //1.创建与原图一模一样大小的bitmap对象,该对象中目前是没有内容的,可以比喻为创建了和原图一样大小的白纸
    Bitmap bmCopy = Bitmap.createBitmap(bmSrc.getWidth(), bmSrc.getHeight(), bmSrc.getConfig());
    //2.创建画笔对象
    Paint paint = new Paint();
    //3.创建画板,把白纸铺到画板上
    Canvas canvas = new Canvas(bmCopy);

    Matrix mt = new Matrix();

    //平移效果,指定平移距离
//        mt.setTranslate(20, 10);
    //缩放效果,指定缩放比例
//        mt.setScale(2, 0.5f, bmCopy.getWidth() / 2, bmCopy.getHeight() / 2);
    //旋转效果
//        mt.setRotate(45, bmCopy.getWidth() / 2, bmCopy.getHeight() / 2);

    //镜面效果
//        mt.setScale(-1, 1);
//        mt.postTranslate(bmCopy.getWidth(), 0);

    //倒影效果
    mt.setScale(1, -1);
    mt.postTranslate(0, bmCopy.getHeight());

    canvas.drawBitmap(bmSrc, mt, paint);

    ImageView iv_src = (ImageView) findViewById(R.id.iv_src);
    iv_src.setImageBitmap(bmSrc);
    ImageView iv_copy = (ImageView) findViewById(R.id.iv_copy);
    iv_copy.setImageBitmap(bmCopy);
}

画板

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Bitmap bmSrc = BitmapFactory.decodeResource(getResources(), R.drawable.bg);
    //白纸
    bmCopy = Bitmap.createBitmap(bmSrc.getWidth(), bmSrc.getHeight(), bmSrc.getConfig());
    //笔
    paint = new Paint();
    //画板
    canvas = new Canvas(bmCopy);
    //作画
    canvas.drawBitmap(bmSrc, new Matrix(), paint);

    iv = (ImageView) findViewById(R.id.iv);
    iv.setImageBitmap(bmCopy);

    iv.setOnTouchListener(new OnTouchListener() {

        //用户手指只要触摸屏幕,就会产生触摸事件
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            //判断触摸事件的类型
            switch (event.getAction()) {
            //手指触摸
            case MotionEvent.ACTION_DOWN:
                //触摸事件中会包含手指触摸的坐标
                startX = (int) event.getX();
                startY = (int) event.getY();
                break;
                //手指滑动
            case MotionEvent.ACTION_MOVE:
                int newX = (int) event.getX();
                int newY = (int) event.getY();
                //指定线的起点和终点
                canvas.drawLine(startX, startY, newX, newY, paint);
                iv.setImageBitmap(bmCopy);

                //把本此画线的终点设置为下一次画线的起点
                startX = newX;
                startY = newY;
                break;
                //手指抬起
            case MotionEvent.ACTION_UP:
                break;

            }
            //true表示告诉系统,这个触摸事件由iv处理
            //false表示不处理该触摸事件,事件往上传递
            return true;
        }
    });
}

public void red(View v){
    paint.setColor(Color.RED);
}

public void green(View v){
    paint.setColor(Color.GREEN);
}

public void brush(View v){
    //改变线条粗细
    paint.setStrokeWidth(8);
}

public void save(View v){
    File file = new File("sdcard/dazuo.png");
    FileOutputStream fos;
    try {
        fos = new FileOutputStream(file);
        //把图片压缩到本地文件
        bmCopy.compress(CompressFormat.PNG, 100, fos);
        fos.close();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    //手动发一个sd卡就绪广播
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_MEDIA_MOUNTED);
    intent.setData(Uri.fromFile(Environment.getExternalStorageDirectory()));
    sendBroadcast(intent);
}

模拟撕衣服

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //加载图片
    Bitmap bmSrc = BitmapFactory.decodeResource(getResources(), R.drawable.big2);
    final Bitmap bmCopy = Bitmap.createBitmap(bmSrc.getWidth(), bmSrc.getHeight(), bmSrc.getConfig());
    Paint paint = new Paint();
    Canvas canvas = new Canvas(bmCopy);
    canvas.drawBitmap(bmSrc, new Matrix(), paint);

    final ImageView iv = (ImageView) findViewById(R.id.iv);
    iv.setImageBitmap(bmCopy);

    iv.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                int x = (int) event.getX();
                int y = (int) event.getY();

                //把该坐标对应的像素,置为透明色
                for (int i = -5; i < 5; i++) {
                    for (int j = -5; j < 5; j++) {
                        if(Math.sqrt(i*i + j*j) <= 5){
                            if(x + i < bmCopy.getWidth() && y + j < bmCopy.getHeight()
                                    && x + i >= 0 && y + j >= 0)
                            //把指定坐标的像素置为指定的颜色
                            bmCopy.setPixel(x + i, y + j, Color.TRANSPARENT);
                        }
                    }
                }
                iv.setImageBitmap(bmCopy);
                break;

            }
            return true;
        }
    });
}

视频播放

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    SurfaceView sv = (SurfaceView) findViewById(R.id.sv);
    //获取surfaceview的控制器
    final SurfaceHolder holder = sv.getHolder();


//      Thread t = new Thread(){
//          @Override
//          public void run() {
//              try {
//                  sleep(200);
//              } catch (InterruptedException e) {
//                  // TODO Auto-generated catch block
//                  e.printStackTrace();
//              }
//              runOnUiThread(new Runnable() {
//                  @Override
//                  public void run() {
//                      MediaPlayer player = new MediaPlayer();
//                      player.reset();
//                      try {
//                          player.setDataSource("sdcard/2.3gp");
//                          //指定视频播放在哪个surfaceview
//                          player.setDisplay(holder);
//                          player.prepare();
//                          player.start();
//                      } catch (Exception e) {
//                          // TODO Auto-generated catch block
//                          e.printStackTrace();
//                      }
//                  }
//              });
//          }
//      };
//      t.start();

    holder.addCallback(new Callback() {
        //surfaceview销毁时会调用
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            if(player != null){
                //停止之前先保存播放进度
                progress = player.getCurrentPosition();
                player.stop();
                player.release();
                player = null;
            }
        }
        //surfaceview创建时会调用
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            if(player == null){
                player = new MediaPlayer();
                player.reset();
                try {
                    player.setDataSource("sdcard/2.3gp");
                    //指定视频播放在哪个surfaceview
                    player.setDisplay(holder);
                    player.prepare();
                    //跳转到上一次停止的地方继续播放
                    player.seekTo(progress);
                    player.start();
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

        }

        //surfaceview结构改变时会调用
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                int height) {
            // TODO Auto-generated method stub

        }
    });
}

VideoView

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    VideoView vv = (VideoView) findViewById(R.id.vv);
    vv.setVideoPath("sdcard/2.3gp");
    vv.start();
}

照相和拍摄

public void click1(View v){
    //启动拍照的Activity
    Intent intent = new Intent();
    intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("sdcard/haha.jpg")));
    startActivityForResult(intent, 10);
}

public void click2(View v){
    //启动拍照的Activity
    Intent intent = new Intent();
    intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File("sdcard/haha2.3gp")));
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

    startActivityForResult(intent, 20);

}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == 10){
        Toast.makeText(this, "拍照完毕", 0).show();
    }
    else if(requestCode == 20){
        Toast.makeText(this, "摄像完毕", 0).show();
    }
}

拍照预览

public class MainActivity extends Activity {

     private Camera mCamera;
        private CameraPreview mPreview;

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

            if(checkCameraHardware(this)){
                // 创建摄像头实例
                mCamera = getCameraInstance();
            }
            else{
                return;
            }
            //创建预览类的对象
            mPreview = new CameraPreview(this, mCamera);
            FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
            //把预览类设置为帧布局的子节点
            preview.addView(mPreview);


         // 给按钮设置点击侦听
            Button captureButton = (Button) findViewById(R.id.button_capture);
            captureButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //自动聚焦
                        mCamera.autoFocus(new AutoFocusCallback() {

                            //聚焦完成调用
                            @Override
                            public void onAutoFocus(boolean success, Camera camera) {
                                 // 拍照
                                mCamera.takePicture(null, null, mPicture);

                            }
                        });

                    }
                }
            );
        }


    /** 检测手机是否有摄像头 */
    private boolean checkCameraHardware(Context context) {
        //检测手机是否安装有摄像头应用
        if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
            // this device has a camera
            return true;
        } else {
            // no camera on this device
            return false;
        }
    }

    /** 一个获取摄像头实例的安全途径 */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open(); // 获取第一个后置摄像头的实例
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }


    private PictureCallback mPicture = new PictureCallback() {

        //拍照会调用此方法
        //data:照片的字节数组
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            try {
                File pictureFile = new File("sdcard/mrplus.jpg");
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.close();
            } catch (FileNotFoundException e) {
                Log.d(CameraPreview.TAG, "File not found: " + e.getMessage());
            } catch (IOException e) {
                Log.d(CameraPreview.TAG, "Error accessing file: " + e.getMessage());
            } finally{
                //拍照完成后重新进入预览
                camera.startPreview();
            }
        }
    };

}

预览类:

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
    public static final String TAG = "camera";
    private SurfaceHolder mHolder;
    private Camera mCamera;

    public CameraPreview(Context context, Camera camera) {
        super(context);
        mCamera = camera;

        // Install a SurfaceHolder.Callback so we get notified when the
        // underlying surface is created and destroyed.
        //获取surfaceview的控制器
        mHolder = getHolder();
        //设置侦听
        mHolder.addCallback(this);
        // deprecated setting, but required on Android versions prior to 3.0
        mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // The Surface has been created, now tell the camera where to draw the preview.
        try {
            //设置摄像头的预览界面显示在holder对应的那个surfaceview
            mCamera.setPreviewDisplay(holder);
            //开始预览
            mCamera.startPreview();
        } catch (IOException e) {
            Log.d(TAG, "Error setting camera preview: " + e.getMessage());
        }
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // empty. Take care of releasing the Camera preview in your activity.
    }

    public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
        // If your preview can change or rotate, take care of those events here.
        // Make sure to stop the preview before resizing or reformatting it.

        if (mHolder.getSurface() == null){
          // preview surface does not exist
          return;
        }

        // 在对surfaceview做改变前,先停止预览
        try {
            mCamera.stopPreview();
        } catch (Exception e){
          // ignore: tried to stop a non-existent preview
        }

        // set preview size and make any resize, rotate or
        // reformatting changes here

        // 设置改变完后,重新开始预览
        try {
            mCamera.setPreviewDisplay(mHolder);
            mCamera.startPreview();

        } catch (Exception e){
            Log.d(TAG, "Error starting camera preview: " + e.getMessage());
        }
    }
}
版权声明:本文为博主原创文章,未经博主允许不得转载。

RESTful

#JAX-RS2入门 1. REST是一种跨平台、跨语言的架构风格 2. 对象被视为一种资源 3. 表征性状态是指资源数据在某个瞬间的状态快照。REST的资源是可寻址的,使用URI在唯一标...

逻辑回归

摘自牛客网, 侵删

安卓小案例收集五(内容提供者、动画)

内容提供者 获取系统短息 插入系统短信 获取系统联系人 插入联系人 内容观察者 Fragment Fragment数据传递 帧动画 补间动画 属性动画内容提供者配置:...

RSS阅读器-安卓小案例

  • 2016年04月17日 18:33
  • 1.95MB
  • 下载

一个大四实习生从安卓小白到可以独自承担安卓和web前端的一年奋斗之旅

这是一篇无关技术的文章,而是对自己整个大四一年工作经验的总结,记录着自己的学习方法和学习习惯,记录着自己从最开始的一个安卓小白,到现在可以独自承担原生安卓项目。记录着自己在工作之余学习H5前端技术,到...

安卓小游戏-猜猜鸡蛋在哪里

  • 2017年11月24日 15:30
  • 17.03MB
  • 下载

BMI测试 安卓小应用

  • 2016年01月20日 12:41
  • 590KB
  • 下载

2.一个随机生成多种颜色并获取颜色RGB值以及对应十六进制的安卓小应用

安卓学习中,每次选择颜色十六进制都让人头大,试着开发一个应用解决这个问题。 实现效果如下图: 主要功能: 1. 随机生成100种颜色(有重复,重复并不影响选择,没喜欢的颜...

安卓小视频压缩代码

  • 2017年08月15日 16:59
  • 47.7MB
  • 下载

安卓小软件

  • 2013年04月06日 13:17
  • 19KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:安卓小案例收集四(多媒体)
举报原因:
原因补充:

(最多只允许输入30个字)