`
xinanadu
  • 浏览: 227514 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

从android系统图库中取图片的代码

 
阅读更多

该文章转载自 http://marshal.easymorse.com/archives/2971

 

 

从android系统图库中取图片的代码

在自己应用中,从系统图库中取图片,然后截取其中一部分,再返回到自己应用中。这是很多有关图片的应用需要的功能。

写了一个示例,上来就是个大按钮,连布局都不要了。最终,用选取图片中的一部分作为按钮的背景。

1 2 3

 

4 5

 

源代码见:

http://easymorse.googlecode.com/svn/tags/android.gallery-1.1

代码贴在下面:

package com.easymorse.gallery;

import java.io.File;

import android.app.Activity; 
import android.content.Intent; 
import android.graphics.drawable.Drawable; 
import android.net.Uri; 
import android.os.Bundle; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button;

public class GalleryActivity extends Activity {

    private static int SELECT_PICTURE;

    private File tempFile;

    Button button;

    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        this.tempFile=new File("/sdcard/a.jpg"); 
        button = new Button(this); 
        button.setText("获取图片"); 
        button.setOnClickListener(new OnClickListener() {

            @Override 
            public void onClick(View v) { 
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
                intent.setType("image/*"); 
                intent.putExtra("crop", "true");

                // intent.putExtra("aspectX", 1); 
                // intent.putExtra("aspectY", 2);

                intent.putExtra("output", Uri.fromFile(tempFile)); 
                intent.putExtra("outputFormat", "JPEG");

                startActivityForResult(Intent.createChooser(intent, "选择图片"), 
                        SELECT_PICTURE); 
            } 
        }); 
        setContentView(button); 
    }

    @Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
        if (resultCode == RESULT_OK) { 
            if (requestCode == SELECT_PICTURE) { 
                button.setBackgroundDrawable(Drawable.createFromPath(tempFile
                        .getAbsolutePath())); 
            } 
        } 
    }

}

 

这里需要注意几点:

  • 从图库中选取出来保存的图片剪辑,需要保存在sd卡目录,不能保存在应用自己的在内存的目录,因为是系统图库来保存这个文件,它没有访问你应用的权限;
  • intent.putExtra("crop", "true")才能出剪辑的小方框,不然没有剪辑功能,只能选取图片;
  • intent.putExtra("aspectX", 1),是剪辑方框的比例,可用于强制图片的长宽比。

该文章转载自 http://marshal.easymorse.com/archives/2971
<!--EndFragment-->

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics