Android平台上利用opencv进行图像的缩放

写了个图像缩放的小程序,仅为使用下opencv for Andorid。

 

在Android2.3.1模拟器运行,程序界面:

Android平台上利用opencv进行图像的缩放

 

 

点击缩小按钮,界面如下:

 

 

 

代码如下:

 

package cn.netava.opencv;

import java.io.File;

import org.opencv.core.CvType;
import org.opencv.core.Mat;
import org.opencv.core.Size;
import org.opencv.highgui.Highgui;
import org.opencv.imgproc.Imgproc;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class ButtonSizeImage extends Activity {

	private Button deal_button;
	private ImageView imgview;
	private Bitmap bm;
	private boolean flag=false;//判断缩放还是恢复,初始值为false

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// 缩放按钮
		deal_button = (Button) this.findViewById(R.id.button1);
		// 存放照片图层
		imgview = (ImageView) this.findViewById(R.id.imageView1);
		// 显示照片
		bm = BitmapFactory.decodeFile("/sdcard/girl.jpg");
		imgview.setImageBitmap(bm);
		
		//匿名内部类,创建缩小事件监听器
		OnClickListener clicklisten=new OnClickListener(){

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if(flag){
					deal_button.setText("缩小");
					flag=false;
					// 显示照片
					bm = BitmapFactory.decodeFile("/sdcard/girl.jpg");
					imgview.setImageBitmap(bm);
				}
				else{ 
					deal_button.setText("恢复");
					flag=true;
					double scale = 0.1; // 缩放比例
					Mat img = Highgui.imread("/sdcard/girl.jpg");// 读入图片,将其转换为Mat
					Size dsize = new Size(img.width() * scale, img.height() * scale); // 设置新图片的大小
					Mat img2 = new Mat(dsize, CvType.CV_16S);// 创建一个新的Mat(opencv的矩阵数据类型)
					Imgproc.resize(img, img2,dsize);//调用Imgproc的Resize方法,进行图片缩放
					 if(Highgui.imwrite("/sdcard/girlnew.jpg", img2)){//将图形保存到new.jpg中
							File f = new File("/sdcard/girlnew.jpg");
							if(f.exists())
							{
								bm=BitmapFactory.decodeFile("/sdcard/girlnew.jpg");
								imgview.setImageBitmap(bm);
								
							}
				        }
				        else{
				        	Toast.makeText(ButtonSizeImage.this, "===========图片缩小失败============!!", 3).show();
				        }	
				}
				}
				
			
		};
		//缩放按钮添加点击事件监听器
		deal_button.setOnClickListener(clicklisten);
		
	}
}

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(android)