Android:打开相册(动态布局,Activity以dialog方式显示,图片压缩)

本文介绍了如何在Android应用中实现从相册选择图片,并以对话框形式展示,同时包含图片的压缩技术。主要代码实现包括相册 Intent 的调用和图片压缩逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果如下:


public class MainActivity extends AppCompatActivity {

    private ImageView img;
    private Button btn;

    public static final int REQUEST = 0x001;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        img = (ImageView) findViewById(R.id.img);
        btn = (Button) findViewById(R.id.btn);

        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,PhotoActivity.class);
                startActivityForResult(intent,REQUEST);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK)
        {
            switch (requestCode)
            {
                case REQUEST:

                    img.setImageBitmap((Bitmap) data.getParcelableExtra(PhotoActivity.DATA));
                    break;
            }
        }
    }
}


主要代码都在这里:

public class PhotoActivity extends AppCompatActivity implements View.OnClickListener{

    private LinearLayout mContentContainer;

    private AppCompatTextView carmero;
    private AppCompatTextView photo;
    private AppCompatTextView mCancel;

    private static final String TEMP_PATH = Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmp/temp_" + System.currentTimeMillis() + ".jpg";
    public static final int REQ_ALBUM = 0x001;
    public static final String ISNULL = "isnull";
    public static final String IMGPATH = "imgpath";
    public static final String DATA = "data";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mContentContainer = new LinearLayout(this);
        mContentContainer.setGravity(Gravity.BOTTOM);
        mContentContainer.setOrientation(LinearLayout.VERTICAL);

        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);

        carmero = new AppCompatTextView(this);
        carmero.setText("相册");
        carmero.setTextColor(Color.BLACK);
        carmero.setTextSize(22);
        carmero.setGravity(Gravity.CENTER);
        carmero.setBackgroundColor(Color.YELLOW);
        carmero.setPadding(0, 10, 0, 10);
        mContentContainer.addView(carmero, params);
        carmero.setOnClickListener(this);

        params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        photo = new AppCompatTextView(this);
        photo.setText("拍照");
        photo.setTextColor(Color.BLACK);
        photo.setTextSize(22);
        photo.setGravity(Gravity.CENTER);
        photo.setBackgroundColor(Color.GREEN);
        photo.setPadding(0, 10, 0, 10);
        mContentContainer.addView(photo, params);

        params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.topMargin = 20;
        mCancel = new AppCompatTextView(this);
        mCancel.setText("取消");
        mCancel.setTextColor(Color.BLACK);
        mCancel.setTextSize(22);
        mCancel.setGravity(Gravity.CENTER);
        mCancel.setPadding(0, 10, 0, 10);
        mCancel.setBackgroundColor(Color.WHITE);
        mContentContainer.addView(mCancel, params);
        mCancel.setOnClickListener(this);

        setContentView(mContentContainer);

        isFolderExists(Environment.getExternalStorageDirectory().getAbsolutePath() + "/tmp/");
        checkFile(TEMP_PATH);
    }

    @Override
    public void onClick(View v)
    {
        if (v == carmero)
        {
            chooseAlbum();
            return;
        }
    }

    boolean isFolderExists(String strFolder)
    {
        File file = new File(strFolder);
        if (!file.exists())
        {
            if (file.mkdirs())
            {
                return true;
            } else
            {
                return false;

            }
        }
        return true;

    }

    private void checkFile(String path)
    {
        File file = new File(path);
        if (!file.exists())
        {
            try
            {
                file.createNewFile();
            } catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    private void chooseAlbum()
    {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, REQ_ALBUM);
    }

    public static Intent setImage(Uri uri, ContentResolver resolver)
    {
        Intent intent = new Intent();

        Cursor cursor = resolver.query(uri, null, null, null, null);

        if (null == cursor)
        {
            intent.putExtra(ISNULL, true);
            return intent;
        }

        if (cursor.moveToFirst())
        {
            intent.putExtra(IMGPATH, cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA)));
        }
        cursor.close();

        return setImage(intent.getStringExtra(IMGPATH), intent);
    }

    public static Intent setImage(String path, Intent intent)
    {
        Log.d("2222", path + "");
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

//        double value = new BigDecimal(options.outWidth).divide(new BigDecimal(options.outHeight), 4, BigDecimal.ROUND_HALF_UP).doubleValue();

        intent.putExtra(ISNULL, false);
        intent.putExtra(IMGPATH, path);
//        intent.putExtra(Constants.ASPECT_RATIO, value == 0d ? "1.0000" : format.format(value));

        options.inJustDecodeBounds = false;

        int be = Math.max(options.outWidth, options.outHeight) / 20;
        if (be % 10 != 0)
            be += 10;
        be = be / 10;
        if (be <= 0)
            be = 1;
        options.inSampleSize = be;
        Bitmap bitmap = BitmapFactory.decodeFile(path, options);
        intent.putExtra(DATA, bitmap);
        return intent;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == RESULT_OK)
        {
            switch (requestCode)
            {
                case REQ_ALBUM:

                    Intent albumIntent = setImage(data.getData(), getContentResolver());
                    if (albumIntent.getBooleanExtra("isnull", true))
                    {
                        Toast.makeText(this, "未找到图片!", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    setResult(RESULT_OK, albumIntent);
                    finish();
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
}

PhotoActivity主题:

 <activity android:name=".PhotoActivity"
            android:theme="@style/DialogBottom"/>

 <style name="AnimBottom" parent="@android:style/Animation">
        <item name="android:windowEnterAnimation">@anim/push_bottom_in</item>
        <item name="android:windowExitAnimation">@anim/push_bottom_out</item>
    </style>

    <style name="DialogBottom" parent="Theme.AppCompat.Light.Dialog">
        <item name="android:windowAnimationStyle">@style/AnimBottom</item>
        <item name="android:windowFrame">@null</item>
        <!-- 边框 -->
        <item name="android:windowIsFloating">false</item>
        <!-- 是否浮现在activity之上 -->
        <item name="android:windowIsTranslucent">true</item>
        <!-- 半透明 -->
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <!-- 无标题 -->
        <item name="android:windowBackground">@android:color/transparent</item>
        <!-- 背景透明 -->
        <item name="android:backgroundDimEnabled">true</item>
        <!-- 模糊 -->
    </style>


push_bottom_in:

<?xml version="1.0" encoding="utf-8"?>
<!-- 上下滑入式 -->
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:duration="200"
        android:fromYDelta="100%"
        android:fromXDelta="0"
        android:toXDelta="0"
        android:toYDelta="0"/>
</set>  

push_bottom_out:

<?xml version="1.0" encoding="utf-8"?>
<!-- 上下滑出式 -->
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="200"
        android:fromXDelta="0"
        android:fromYDelta="0"
        android:toXDelta="0"
        android:toYDelta="100%"/>
</set>

最后别忘了添加权限:

  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值