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

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

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

这里需要注意几点:

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

代码片段(2)

[图片] 2_thumb.png

[代码] [Java]代码

01package com.easymorse.gallery;
02 
03import java.io.File;
04 
05import android.app.Activity;
06import android.content.Intent;
07import android.graphics.drawable.Drawable;
08import android.net.Uri;
09import android.os.Bundle;
10import android.view.View;
11import android.view.View.OnClickListener;
12import android.widget.Button;
13 
14public class GalleryActivity extends Activity {
15 
16    private static int SELECT_PICTURE;
17 
18    private File tempFile;
19 
20    Button button;
21 
22    /** Called when the activity is first created. */
23    @Override
24    public void onCreate(Bundle savedInstanceState) {
25        super.onCreate(savedInstanceState);
26        this.tempFile=new File("/sdcard/a.jpg");
27        button = new Button(this);
28        button.setText("获取图片");
29        button.setOnClickListener(new OnClickListener() {
30 
31            @Override
32            public void onClick(View v) {
33                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
34                intent.setType("image/*");
35                intent.putExtra("crop", "true");
36 
37                // intent.putExtra("aspectX", 1);
38                // intent.putExtra("aspectY", 2);
39 
40                intent.putExtra("output", Uri.fromFile(tempFile));
41                intent.putExtra("outputFormat", "JPEG");
42 
43                startActivityForResult(Intent.createChooser(intent, "选择图片"),
44                        SELECT_PICTURE);
45            }
46        });
47        setContentView(button);
48    }
49 
50    @Override
51    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
52        if (resultCode == RESULT_OK) {
53            if (requestCode == SELECT_PICTURE) {
54                button.setBackgroundDrawable(Drawable.createFromPath(tempFile
55                        .getAbsolutePath()));
56            }
57        }
58    }
59 
60}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值