android发布图片并显示
2017-09-17 17:30:11 zcn596785154 阅读数 588

1,下载ImageLoad.jar包放入项目libs文件夹中,并点击右键—>add as Library

2,首先记得在Manifest.xml注册权限(注:6.0以后的版本要在代码中动态注册权限)

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

3,布局文件,一个ImageView用来显示加载的图片,Button点击后进入系统相册选取图片

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.zcn.demo.loadgallerypicture.MainActivity">

    <ImageView
        android:id="@+id/pic"
        android:src="@mipmap/ic_launcher"
        android:layout_width="120dp"
        android:layout_height="120dp" />
    <Button
        android:id="@+id/btn"
        android:layout_width="match_parent"
        android:layout_height="48dp"
        android:layout_gravity="bottom"
        android:text="button"/>
</LinearLayout>

4,.java文件

package com.zcn.demo.loadgallerypicture;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private static int WRITE_SD_CODE = 1;
    private static int READ_SD_CODE = 2;
    private static String TAG = "ZCN_MainActivity";
    private ImageView image;
    private Button btn;

    private String pic_path;
    private DisplayImageOptions options;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        image = (ImageView)findViewById(R.id.pic);
        btn = (Button)findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                requestPermission();
            }
        });
    }

    //android 6.0 以上版本要手动要求权限
    @TargetApi(Build.VERSION_CODES.M)
    private void requestPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            this.requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},READ_SD_CODE);
        }else {
            Log.v(TAG, "6.0一下版本直接打开相册....");
            Intent intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, ActivityRequestCode.SHOW_MAP_DEPOT);
        }
    }

    //权限选择结果接收
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == READ_SD_CODE) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户授予了此权限
                // 调用android自带的图库
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, ActivityRequestCode.SHOW_MAP_DEPOT);
            } else {
                // 用户拒绝了此权限
            }
        }
    }

    public interface ActivityRequestCode {
        public static final int SHOW_MAP_DEPOT = 1; //显示Android自带图库,用于选择用户自己的图片
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (requestCode == ActivityRequestCode.SHOW_MAP_DEPOT
                    && resultCode == Activity.RESULT_OK)
                showPic(resultCode,data);
        }
    }

    // 调用android自带图库,显示选中的图片
    private void showPic(int resultCode,Intent data) {
        if(resultCode== Activity.RESULT_OK) {
            if (data!=null) {
                Uri uri = data.getData();
                Log.v(TAG, "uri = "+uri);
                if (uri!=null) {
                    Cursor cursor = getContentResolver().query(uri, null, null, null, null);
                    //选择的就只是一张图片,所以cursor只有一条记录
                    if (cursor != null) {
                        if (cursor.moveToFirst()) {
                            String path = cursor.getString(cursor.getColumnIndex("_data"));//获取相册路径字段
                            Log.v(TAG, "打开相册获取的图片sd卡路径:" + path);
                            File file = new File(path);
                            initOptions();
                            ImageLoader.getInstance().displayImage(uri.toString(), image,options);
                            //保存图片到data/data/files文件夹下
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = true;
                            Bitmap bitmap = BitmapFactory.decodeFile(path, options);
                            File f = getFileStreamPath("ic_mine_head_portrait.jpg");
                            Log.d(TAG, "File path :" + file.getParentFile());
                            if (!f.exists()) {
                                Log.d(TAG, "文件不存在");
                                FileOutputStream out = null;
                                try{
                                    f.createNewFile();
                                    out = new FileOutputStream(f);
                                    if(bitmap.compress(Bitmap.CompressFormat.PNG, 90, out))
                                    {
                                        out.flush();
                                        out.close();
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }finally {
                                    try {
                                        out.close();
                                    } catch (IOException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }else{
            Log.d(TAG,"放弃从相册选择");
        }
    }

    private void initOptions(){
        options = new DisplayImageOptions.Builder().showStubImage(R.mipmap.ic_main_ad_stub) // 设置图片下载期间显示的图片
                .showImageForEmptyUri(R.mipmap.ic_main_ad_empty) // 设置图片Uri为空或是错误的时候显示的图片
                .showImageOnFail(R.mipmap.ic_main_ad_error) // 设置图片加载或解码过程中发生错误显示的图片
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisc(true) // 设置下载的图片是否缓存在SD卡中
                // .displayer(new RoundedBitmapDisplayer(20)) // 设置成圆角图片
                .build(); // 创建配置过得DisplayImageOption对象

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(this.getApplicationContext()).defaultDisplayImageOptions(options)
                .threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }
}

后续:显示图片所使用的uri:

String imageUri = "http://site.com/image.png"; // from Web
String imageUri = "file:///mnt/sdcard/image.png"; // from SD card
String imageUri = "content://media/external/audio/albumart/13"; // from content provider
String imageUri = "assets://image.png"; // from assets
String imageUri = "drawable://" + R.drawable.image; // from drawables (only images, non-9patch)

注意:使用drawable://除非你真的需要他。时刻要注意使用本地图片加载方法:setImageResource带代替ImageLoader。

2015-08-06 00:05:15 gcsky5211 阅读数 1080
package com.sdcard_read_all;


import java.io.File;
import java.util.ArrayList;


import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;


public class MainActivity extends Activity {
private TextView textView1;
private GridView gridView1;
private static Handler handler;
// 用于存放sdcard卡上的所有图片路径
public static ArrayList<String> dirAllStrArr = new ArrayList<String>();


// 用于遍历sdcard卡上所有文件的类
public static void DirAll(File dirFile) throws Exception {
if (dirFile.exists()) {
File files[] = dirFile.listFiles();
for (File file : files) {
String fileName = file.getName();
String filePath = file.getPath();
Message msg = new Message();
msg.obj = "正在读取:" + filePath;
handler.sendMessage(msg);
if (file.isDirectory()) {


// 除sdcard上Android这个文件夹以外。
if (!fileName.endsWith("Android")) {
// 如果遇到文件夹则递归调用。
DirAll(file);
}
} else {
// 如果是图片文件压入数组


if (fileName.endsWith(".jpg") || fileName.endsWith(".jpeg")
|| fileName.endsWith(".bmp")
|| fileName.endsWith(".gif")
|| fileName.endsWith(".png")) {
// 如果遇到文件则放入数组
if (dirFile.getPath().endsWith(File.separator)) {
dirAllStrArr
.add(dirFile.getPath() + file.getName());
} else {
dirAllStrArr.add(dirFile.getPath() + File.separator
+ file.getName());
}
}
}
}
}
}


// 图片加载的缓存工具类,安卓自带的方法
public static BitmapFactory.Options getHeapOpts(File file) {
BitmapFactory.Options opts = new BitmapFactory.Options();
// 数字越大读出的图片占用的heap必须越小,不然总是溢出
if (file.length() < 20480) { // 0-20k
opts.inSampleSize = 1;// 这里意为缩放的大小 ,数字越多缩放得越厉害
} else if (file.length() < 51200) { // 20-50k
opts.inSampleSize = 2;
} else if (file.length() < 307200) { // 50-300k
opts.inSampleSize = 4;
} else if (file.length() < 819200) { // 300-800k
opts.inSampleSize = 6;
} else if (file.length() < 1048576) { // 800-1024k
opts.inSampleSize = 8;
} else {
opts.inSampleSize = 10;
}
return opts;
}


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
gridView1 = (GridView) findViewById(R.id.gridView1);
gridView1.setVisibility(View.INVISIBLE);
/* 遍历sdcard旗下的所有文件夹开始 */


Thread readSdcard = new Thread() {
private String sdpath = Environment.getExternalStorageDirectory()
.getAbsolutePath();// 获取sdcard的根路径
private File dirFile = new File(sdpath);


public void run() {
try {
DirAll(dirFile);
Message msg = new Message();
msg.obj = "0";
handler.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
}
};
};
textView1.setVisibility(View.VISIBLE);
readSdcard.start();


/* 遍历sdcard旗下的所有文件夹结束 */
// 不停在接受定时器的消息,根据消息的参数,进行处理


handler = new Handler(new Handler.Callback() {// 这样写,就不弹出什么泄漏的警告了
@Override
public boolean handleMessage(Message msg) {
textView1.setText(msg.obj + "");
if (msg.obj.equals("0")) {
textView1.setVisibility(View.GONE);
gridView1.setVisibility(View.VISIBLE);
}
return false;
}
});


BaseAdapter baseAdapter = new BaseAdapter() {


@Override
public View getView(int position, View convertView, ViewGroup arg2) {
ImageView imageView1;
if (convertView == null) {
imageView1 = new ImageView(MainActivity.this);
imageView1.setAdjustViewBounds(true);// 自动缩放为宽高比
imageView1.setScaleType(ScaleType.CENTER_INSIDE);// 设置图片保持宽高比显示
imageView1.setPadding(5, 5, 5, 5);
} else {
imageView1 = (ImageView) convertView;
}
String filePath = dirAllStrArr.get(position);
File file = new File(filePath);
Bitmap bm = BitmapFactory.decodeFile(filePath,
getHeapOpts(file));
imageView1.setImageBitmap(bm);


return imageView1;
}


// 获取当前选项
@Override
public long getItemId(int position) {
return position;
}


@Override
public Object getItem(int position) {
return position;
}


// 获取数量
@Override
public int getCount() {
return dirAllStrArr.size();
}
};
gridView1.setAdapter(baseAdapter);// 把适配器与网格视图链接起来
gridView1.setOnItemClickListener(new OnItemClickListener() {// 点击网格组件的任意一张图片时候的事件
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position,// position为点击的id
long arg3) {
Intent intent = new Intent(MainActivity.this,
ViewActivity.class);// 激活ViewActivity
Bundle bundle = new Bundle();
bundle.putString("imgPath", dirAllStrArr.get(position));// 传递点击的图片的id到ViewActivity
intent.putExtras(bundle);
startActivity(intent);
}
});
}


// 创建menu的方法,没有该方法,不会在右上角设置菜单。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// 设置menu界面为res\menu\menu.xml
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


// 处理菜单事件
public boolean onOptionsItemSelected(MenuItem item) {
// 得到当前选中的MenuItem的ID,
int item_id = item.getItemId();
switch (item_id) {
// 设置id为menu_exit的菜单子项所要执行的方法。
case R.id.menu_exit:
System.exit(0);// 结束程序
break;
}
return true;
}


// 对物理按钮的监听
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
finish();// 关闭这个Activity。
break;
}
return super.onKeyDown(keyCode, event);
}


}





ackage com.sdcard_read_all;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;


public class ViewActivity extends Activity {
private TextView textView1;
private ImageView imageView1;
private Button button1;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view);
textView1 = (TextView) findViewById(R.id.textView1);
imageView1 = (ImageView) findViewById(R.id.imageView1);
button1 = (Button) findViewById(R.id.button1);
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String imgPath = bundle.getString("imgPath");
textView1.setText("图片路径:" + imgPath);
Bitmap bm = BitmapFactory.decodeFile(imgPath);
imageView1.setImageBitmap(bm);
button1.setOnClickListener(new OnClickListener() {


@Override
public void onClick(View arg0) {
finish();
}
});


}


// 对物理按钮的监听
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
finish();// 关闭这个Activity。
break;
}
return super.onKeyDown(keyCode, event);
}
}

2019-04-02 16:12:45 ITzhongzi 阅读数 91

需求描述: 选择手机相册中的一张图片,并通过ImageView展示出来

参考博文: android打开手机相册获取真正的图片路径

效果展示:

示例代码:

MainActivity

package com.example.www.mutilmedia;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import java.util.Arrays;

public class MainActivity extends AppCompatActivity {

    String[] mPermissionList = new String[]{
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE};
    public static final int REQUEST_PICK_IMAGE = 11101;
    private ImageView mShowImg;

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

        mShowImg = (ImageView) findViewById(R.id.imageView);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case 100:
                boolean writeExternalStorage = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                boolean readExternalStorage = grantResults[1] == PackageManager.PERMISSION_GRANTED;
                Log.e("MainActivity", Arrays.toString(grantResults));
                if (grantResults.length > 0 && writeExternalStorage && readExternalStorage) {
                    getImage();
                } else {
                    Toast.makeText(this, "请设置必要权限", Toast.LENGTH_SHORT).show();
                }

                break;
        }
    }

    private void getImage() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            startActivityForResult(new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"),
                    REQUEST_PICK_IMAGE);
        } else {
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            intent.setType("image/*");
            startActivityForResult(intent, REQUEST_PICK_IMAGE);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case REQUEST_PICK_IMAGE:
                    if (data != null) {
                        String realPathFromUri = RealPathFromUriUtils.getRealPathFromUri(this, data.getData());
                        Log.e("MainActivity", realPathFromUri);
                        showImg(realPathFromUri);
                    } else {
                        Toast.makeText(this, "图片损坏,请重新选择", Toast.LENGTH_SHORT).show();
                    }

                    break;
            }
        }
    }


    public void openCamera(View view) {
        ActivityCompat.requestPermissions(MainActivity.this, mPermissionList, 100);
    }


    public void showImg(String path){
        Bitmap bitmap = BitmapFactory.decodeFile(path);
        mShowImg.setImageBitmap(bitmap);
    }

}

  • RealPathFromUriUtils
package com.example.www.mutilmedia;

import android.annotation.SuppressLint;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

public class RealPathFromUriUtils {
    /**
     * 根据Uri获取图片的绝对路径
     *
     * @param context 上下文对象
     * @param uri     图片的Uri
     * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
     */
    public static String getRealPathFromUri(Context context, Uri uri) {
        int sdkVersion = Build.VERSION.SDK_INT;
        if (sdkVersion >= 19) { // api >= 19
            return getRealPathFromUriAboveApi19(context, uri);
        } else { // api < 19
            return getRealPathFromUriBelowAPI19(context, uri);
        }
    }

    /**
     * 适配api19以下(不包括api19),根据uri获取图片的绝对路径
     *
     * @param context 上下文对象
     * @param uri     图片的Uri
     * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
     */
    private static String getRealPathFromUriBelowAPI19(Context context, Uri uri) {
        return getDataColumn(context, uri, null, null);
    }

    /**
     * 适配api19及以上,根据uri获取图片的绝对路径
     *
     * @param context 上下文对象
     * @param uri     图片的Uri
     * @return 如果Uri对应的图片存在, 那么返回该图片的绝对路径, 否则返回null
     */
    @SuppressLint("NewApi")
    private static String getRealPathFromUriAboveApi19(Context context, Uri uri) {
        String filePath = null;
        if (DocumentsContract.isDocumentUri(context, uri)) {
            // 如果是document类型的 uri, 则通过document id来进行处理
            String documentId = DocumentsContract.getDocumentId(uri);
            if (isMediaDocument(uri)) { // MediaProvider
                // 使用':'分割
                String id = documentId.split(":")[1];

                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = {id};
                filePath = getDataColumn(context, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection, selectionArgs);
            } else if (isDownloadsDocument(uri)) { // DownloadsProvider
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(documentId));
                filePath = getDataColumn(context, contentUri, null, null);
            }
        } else if ("content".equalsIgnoreCase(uri.getScheme())) {
            // 如果是 content 类型的 Uri
            filePath = getDataColumn(context, uri, null, null);
        } else if ("file".equals(uri.getScheme())) {
            // 如果是 file 类型的 Uri,直接获取图片对应的路径
            filePath = uri.getPath();
        }
        return filePath;
    }

    /**
     * 获取数据库表中的 _data 列,即返回Uri对应的文件路径
     *
     * @return
     */
    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        String path = null;

        String[] projection = new String[]{MediaStore.Images.Media.DATA};
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                path = cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return path;
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is MediaProvider
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is DownloadsProvider
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }
}

  • activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginBottom="8dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/button3"
        app:srcCompat="@android:color/white" />

    <Button
        android:id="@+id/button3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="8dp"
        android:layout_marginTop="16dp"
        android:layout_marginEnd="8dp"
        android:onClick="openCamera"
        android:text="camera"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.048"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>
  • AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.www.mutilmedia">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
2014-02-20 16:45:14 xiaoyi848699 阅读数 1750

之前做一个项目的时候需要1.从SD卡读取图片转为预览图(点阵图,类似马赛克),2.保存当前预览图到特定文件夹,保存为一个txt,txt里存的是像素矩阵。3.从那个特定文件夹里读取像素矩阵,显示为预览图。

今天一下午和一晚上都在纠结第3个任务。终于搞定了。

bmp=Bitmap.createBitmap(Bitmap2, width*size, height*size, Bitmap.Config.ARGB_8888);

第4个参数..蛋疼,之前写成bmp.getConfig(),一运行就意外停止。这个函数的作用就是把像素矩阵转为bitmap,之后在imageView中显示。

Android从SD卡读取图片并显示为点阵图

Android从SD卡读取图片并显示为点阵图

Android从SD卡读取图片并显示为点阵图

Android从SD卡读取图片并显示为点阵图

Android从SD卡读取图片并显示为点阵图

Android从SD卡读取图片并显示为点阵图

Android从SD卡读取图片并显示为点阵图


Android从SD卡读取图片并显示为点阵图


Activity01Activity.java :

 

package zhang.zhuoyueBei.SDCardFileExplorerAndFileToBitMap;

import zhang.zhuoyueBei.SDCardFileExplorerAndFileToBitMap.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class Activity01Activity extends Activity {
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
       
       
       
        Button button3=(Button) findViewById(R.id.button3);
        button3.setOnClickListener(new Button.OnClickListener() {
   public void onClick(View v)
   {
    
    Intent intent = new Intent();
    
    intent.setClass(Activity01Activity.this, FileToBitMapActivity.class);
    
    startActivity(intent);
    
    Activity01Activity.this.finish();
   }
        });
    }
   
   
    @Override
    public void onStart()
 {
  super.onStart();
 }
    @Override
 public void onResume()
 {
  super.onResume();
 }
    @Override
 public void onPause()
 {
  super.onPause();
 }
    @Override
 public void onStop()
 {
  super.onStop();
 }
    @Override
 public void onDestroy()
 {
  super.onDestroy();
 }
    @Override
 public void onRestart()
 {
  super.onRestart();
 }
   
   
}

 

 

 

FileToBitMapActivity.java :

 

 

package zhang.zhuoyueBei.SDCardFileExplorerAndFileToBitMap;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import zhang.zhuoyueBei.SDCardFileExplorerAndFileToBitMap.R;


import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.graphics.Matrix;
public class FileToBitMapActivity extends Activity
{
 String SDcardPath;
 String FolderPath;
 
 String filePath;
 int state=0;//0 没参数,1 取得imagepath,2取得资源文件path
 
 int width=16;
 int height;
 
    int initWidth;
    int initHeight;

 
    Bitmap bmp;
   
    int[] Bitmap1;//缩放后16行的像素矩阵
   
    int size=20;//1格点阵的边长
    int[] Bitmap2;//缩略图
    String res=null;
   
    ImageView mImageView;
   
   

   
    public String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()  
                            .equals(android.os.Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
        if   (sdCardExist)  
                                    
          sdDir = Environment.getExternalStorageDirectory();//获取根目录
       
        return sdDir.toString();
       
 }
   
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.filetobitmap);
  
  SDcardPath=getSDPath();
  FolderPath=SDcardPath+"/MagicSwing";
  
  Bundle bundle= new Bundle();
  bundle=this.getIntent().getExtras();
  if(bundle!=null){
  filePath=bundle.getString("filePath");
  state=bundle.getInt("state");
  if(state==1){
   
      Bitmap   image = BitmapFactory.decodeFile(filePath);
      initWidth = image.getWidth();
      initHeight = image.getHeight();
      float scale=((float)width)/initWidth;
      height=(int)(initHeight*scale);
        
         //将image缩放后存在bmp中
         Matrix matrix=new Matrix();
         //缩放矩阵
         matrix.postScale(scale,scale);
         //缩放
   bmp=Bitmap.createBitmap(image,0,0,initWidth,initHeight,matrix,true);
        
   //得到缩放后的像素矩阵
   Bitmap1=new int[width*height];
   bmp.getPixels(Bitmap1,0,width,0,0,width,height);
  }
  
  else if(state==2)
  {
    File file = new File(FolderPath+"/res.txt");
   if(file.exists()) 
   {
       try{
        FileInputStream fi = new FileInputStream(FolderPath+"/res.txt"); 
        BufferedReader br = new BufferedReader(new InputStreamReader(fi)); 


        String readString = new String(); 

            while ((readString = br.readLine()) != null) { 

                  //数据多的话须要在这里处理 readString 
           res+=readString;

           

       }catch (Exception e)
       {
       }
   
   
   if(res!=null){
    res=res.substring(5);
    int len=0;
    int cur=0;
    int num=1;
    for(int i=0;i<res.length();i++)
     if(res.charAt(i)==' ')
      num++;
    Bitmap1=new int[num];
    String tmp=new String();
    for(int i=0;i<res.length();i++){
     while(i<res.length()&&res.charAt(i)!=' ')
     {
      i++;
      len++;
     }
     tmp=res.substring(i-len,i);
     
     Bitmap1[cur++]=Integer.parseInt(tmp);
     len=0;
    }
    height=cur/width; 

  }
  }
   Bitmap2=new int[width*height*size*size];   
   
   res=new String();
   for(int i=0;i<width;i++)
    for(int j=0;j<height;j++)
    {
        int RGB=Bitmap1[i+j*width];
        for(int ii=i*size;ii<(i+1)*size;ii++)
         for(int jj=j*size;jj<(j+1)*size;jj++)
          Bitmap2[ii+jj*width*size]=RGB;

    }
   res="";
   for(int i=0;i<height;i++){
    
    for(int j=0;j<width;j++)
    {
     int RGB=Bitmap1[j+i*width];
        res+=" "+RGB;
    }
   }
    
  


           //这一句出错
   //bmp=Bitmap.createBitmap(Bitmap2, width*size, height*size, bmp.getConfig());
   bmp=Bitmap.createBitmap(Bitmap2, width*size, height*size, Bitmap.Config.ARGB_8888);
   
   mImageView=(ImageView)findViewById(R.id.imageView1);
   mImageView.setImageBitmap(bmp);
   
   //Canvas canvas=new Canvas();
   //canvas.drawBitmap(Bitmap2, 0, width*size, 0, 0, width*size, height*size, false, null);
    
   
   
  }

  
  
   Button button5=(Button) findViewById(R.id.imageImport);
         button5.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v)
    {
     
     Intent intent = new Intent();
     
     intent.setClass(FileToBitMapActivity.this, SDCardFileExplorerActivity.class);
     Bundle bundle=new Bundle();
     bundle.putBoolean("imageORresfile",true);
     intent.putExtras(bundle);
     
     
     startActivity(intent);
     
     FileToBitMapActivity.this.finish();
    }
         });
        
         Button button6=(Button) findViewById(R.id.resFileImport);
         button6.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v)
    {
     
     Intent intent = new Intent();
     
     
     intent.setClass(FileToBitMapActivity.this, SDCardFileExplorerActivity.class);
     
     
     Bundle bundle=new Bundle();
     bundle.putBoolean("imageORresfile",false);
     intent.putExtras(bundle);
     
     startActivity(intent);
     
     FileToBitMapActivity.this.finish();
    }
         });
        
         Button button7=(Button) findViewById(R.id.save);
         button7.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v)
    {
     
     FileOutputStream stream = null;
     try{
      File file = new File(FolderPath, "res.txt");
      if(!file.exists())
       file.createNewFile();
      stream = new FileOutputStream(file);

     }catch( FileNotFoundException e){
      
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }


     try{
      stream.write( res.getBytes() );
     }catch( IOException e ){
     }

     try{
      stream.close();
     }catch( IOException e ){
      
     }
     
    }
         });
        
        
         Button button8=(Button) findViewById(R.id.done);
         button8.setOnClickListener(new Button.OnClickListener() {
    public void onClick(View v)
    {
            
    }
         });
    }
   
   
    @Override
    public void onStart()
 {
  super.onStart();
 }
    @Override
 public void onResume()
 {
  super.onResume();
 }
    @Override
 public void onPause()
 {
  super.onPause();
 }
    @Override
 public void onStop()
 {
  super.onStop();
 }
    @Override
 public void onDestroy()
 {
  super.onDestroy();
 }
    @Override
 public void onRestart()
 {
  super.onRestart();
 }
 

}
 

 

SDCardFileExplorerActivity.java :

 

package zhang.zhuoyueBei.SDCardFileExplorerAndFileToBitMap;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import zhang.zhuoyueBei.SDCardFileExplorerAndFileToBitMap.R;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class SDCardFileExplorerActivity extends Activity {

 private TextView tvpath;
 private ListView lvFiles;
 private Button btnParent;
   
 Boolean imageORresfile;
 // 记录当前的父文件夹
 File currentParent;

 // 记录当前路径下的所有文件夹的文件数组
 File[] currentFiles;
   
 String SDCardPath;
 String folderPath; 
 
 public String getSDPath(){
        File sdDir = null;
        boolean sdCardExist = Environment.getExternalStorageState()  
                            .equals(android.os.Environment.MEDIA_MOUNTED);   //判断sd卡是否存在
        if   (sdCardExist)  
                                    
          sdDir = Environment.getExternalStorageDirectory();//获取根目录
       
        return sdDir.toString();
       
 }
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.sdcardfileexplorer);
  
  
  Bundle bundle= new Bundle();
  bundle=this.getIntent().getExtras();
  if(bundle!=null){
   imageORresfile=bundle.getBoolean("imageORresfile");
  }

  lvFiles = (ListView) this.findViewById(R.id.files);

  tvpath = (TextView) this.findViewById(R.id.tvpath);
  btnParent = (Button) this.findViewById(R.id.btnParent);

  SDCardPath=getSDPath();
  folderPath=SDCardPath+"/MagicSwing";
  
  
  // 获取系统的SDCard的目录
  File root = new File(SDCardPath);
  
  // 如果SD卡存在的话
  if (root.exists()) {
           
   if(imageORresfile){
   currentParent = root;
   currentFiles = root.listFiles();
   }
   else
   {
    currentParent =new File(folderPath);
    currentFiles= currentParent.listFiles();
   }
   // 使用当前目录下的全部文件、文件夹来填充ListView
   inflateListView(currentFiles);
           
  }

  lvFiles.setOnItemClickListener(new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> adapterView, View view,
     int position, long id) {
    // 如果用户单击了文件,直接返回,不做任何处理
    if (currentFiles[position].isFile()) {
     // 也可自定义扩展打开这个文件等
     String name=currentFiles[position].getName();
     int i;
     for(i=0;i<name.length();i++)
      if(name.charAt(i)=='.')
       break;
     String suffix;
     suffix=String.valueOf(name.toCharArray(), i+1, name.length()-i-1); 
     if(((suffix.equals("jpg")||suffix.equals("bmp")||suffix.equals("jpeg")||suffix.equals("png"))&&imageORresfile)||(suffix.equals("txt")&&!imageORresfile)) {
      String imagePath=new String();
      try {
       imagePath = currentParent.getCanonicalPath()+"/"+name;
      } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
      
      
      Intent intent=new Intent();
      intent.setClass(SDCardFileExplorerActivity.this,FileToBitMapActivity.class);
      Bundle bundle=new Bundle();
      bundle.putString("filePath", imagePath);
      if(!suffix.equals("txt"))
      bundle.putInt("state",1);
      else
       bundle.putInt("state",2);
      intent.putExtras(bundle);
      startActivity(intent);
      SDCardFileExplorerActivity.this.finish();
     }
     else
      Toast.makeText(SDCardFileExplorerActivity.this,
        "不支持的格式", Toast.LENGTH_LONG).show();
     
     
     return;
    }

    // 获取用户点击的文件夹 下的所有文件
    File[] tem = currentFiles[position].listFiles();
    if (tem == null || tem.length == 0) {

     Toast.makeText(SDCardFileExplorerActivity.this,
       "当前路径不可访问或者该路径下没有文件", Toast.LENGTH_LONG).show();
    } else {
     // 获取用户单击的列表项对应的文件夹,设为当前的父文件夹
     currentParent = currentFiles[position];
     // 保存当前的父文件夹内的全部文件和文件夹
     currentFiles = tem;
     // 再次更新ListView
     inflateListView(currentFiles);
    }

   }
  });

  // 获取上一级目录
  btnParent.setOnClickListener(new View.OnClickListener() {

   @Override
   public void onClick(View v) {

    try {

     if (!currentParent.getCanonicalPath().equals(SDCardPath)) {
                       
      
      // 获取上一级目录
      currentParent = currentParent.getParentFile();
      // 列出当前目录下的所有文件
      currentFiles = currentParent.listFiles();
      // 再次更新ListView
      inflateListView(currentFiles);
     }
    } catch (Exception e) {
     // TODO: handle exception
    }

   }
  });

 }

 
 private void inflateListView(File[] files) {

  List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();

  for (int i = 0; i < files.length; i++) {

   Map<String, Object> listItem = new HashMap<String, Object>();

   if (files[i].isDirectory()) {
    // 如果是文件夹就显示的图片为文件夹的图片
    listItem.put("icon", R.drawable.folder);
   } else {
    listItem.put("icon", R.drawable.file);
   }
   // 添加一个文件名称
   listItem.put("filename", files[i].getName());

   File myFile = new File(files[i].getName());

   // 获取文件的最后修改日期
   long modTime = myFile.lastModified();
   SimpleDateFormat dateFormat = new SimpleDateFormat(
     "yyyy-MM-dd HH:mm:ss");
   System.out.println(dateFormat.format(new Date(modTime)));

   // 添加一个最后修改日期
   listItem.put("modify",
     "修改日期:" + dateFormat.format(new Date(modTime)));

   listItems.add(listItem);

  }

  // 定义一个SimpleAdapter
  SimpleAdapter adapter = new SimpleAdapter(
    SDCardFileExplorerActivity.this, listItems, R.layout.list_item,
    new String[] { "filename", "icon", "modify" }, new int[] {
      R.id.file_name, R.id.icon, R.id.file_modify });

  // 填充数据集
  lvFiles.setAdapter(adapter);

  try {
   tvpath.setText("当前路径为:" + currentParent.getCanonicalPath());
  } catch (Exception e) {
   e.printStackTrace();
  }

 }
 
 
 
 
    @Override
    public void onStart()
 {
  super.onStart();
 }
    @Override
 public void onResume()

2012-08-23 11:49:40 ah200614435 阅读数 1207

注意:如果你在模拟器已经启动的情况下,push了几张图片到SDCard中[试过:mnt/sdcard/Picture路径下],建议将模拟器关了,再重新启动一下,否则,刚刚添加的图片,是没有办法获取到的。这是因为Android是在系统启动的时候来扫描模拟器上SDCard中多媒体文件的。


代码:

  1. import android.app.Activity;  
  2. import android.database.Cursor;  
  3. import android.graphics.Bitmap;  
  4. import android.graphics.BitmapFactory;  
  5. import android.os.Bundle;  
  6. import android.provider.MediaStore.Images.Media;  
  7. import android.util.Log;  
  8. import android.view.View;  
  9. import android.widget.ImageButton;  
  10. import android.widget.TextView;  
  11.   
  12. public class PhotoManage extends Activity {  
  13.     private static final float DISPLAY_WIDTH = 200;  
  14.     private static final float DISPLAY_HEIGHT = 200;  
  15.       
  16.     private ImageButton photoView;  
  17.     private TextView nameView;  
  18.     private Cursor cursor;  
  19.       
  20.     private String photoPath;  
  21.     private Bitmap currPhoto;  
  22.       
  23.     //三个变量 用来保存Media.DATA, Media.TITLE,Media.DISPLAY_NAME的索引号,来获取每列的数据   
  24.     private int photoIndex;  
  25.     private int nameIndex;  
  26.       
  27.     @Override  
  28.     public void onCreate(Bundle savedInstanceState) {  
  29.         super.onCreate(savedInstanceState);  
  30.         setContentView(R.layout.main);  
  31.           
  32.         photoView = (ImageButton)this.findViewById(R.id.image_view);    
  33.         photoView.setOnClickListener(clickListener);    
  34.         nameView = (TextView)this.findViewById(R.id.view_name);   
  35.           
  36.         //指定获取的列     
  37.         String columns[] = new String[]{    
  38.                 Media.DATA,Media._ID,Media.TITLE,Media.DISPLAY_NAME    
  39.         };    
  40.         cursor = this.getContentResolver().query(Media.EXTERNAL_CONTENT_URI, columns, nullnullnull);    
  41.         photoIndex = cursor.getColumnIndexOrThrow(Media.DATA);    
  42.         nameIndex = cursor.getColumnIndexOrThrow(Media.DISPLAY_NAME);    
  43.             
  44.         Log.v("HERE First:""First Debug");    
  45.         //显示第一张图片,但是首先要判断一下,Cursor是否有值     
  46.         if(cursor.moveToFirst()){    
  47.             showImage();    
  48.         }    
  49.     }  
  50.       
  51.     private View.OnClickListener clickListener = new View.OnClickListener() {  
  52.           
  53.         @Override  
  54.         public void onClick(View v) {  
  55.             // TODO Auto-generated method stub   
  56.             if(cursor.moveToNext()){  
  57.                 showImage();  
  58.             }  
  59.         }  
  60.     };  
  61.     /** 
  62.      * 显示图像 
  63.      */  
  64.     private void showImage(){  
  65.         photoPath = cursor.getString(photoIndex); //获取图片存储位置   
  66.           
  67.         Log.v("Photo Path:", photoPath);  
  68.         currPhoto = decodeBitmap(photoPath);  
  69.         photoView.setImageBitmap(currPhoto);  
  70.         nameView.setText(cursor.getString(nameIndex));  
  71.     }  
  72.       
  73.     /** 
  74.      * 从path中获取图片信息 
  75.      * @param path 
  76.      * @return 
  77.      */  
  78.     private Bitmap decodeBitmap(String path){  
  79.         BitmapFactory.Options op = new BitmapFactory.Options();    
  80.         op.inJustDecodeBounds = true;    
  81.         Bitmap bmp = BitmapFactory.decodeFile(path, op); //获取尺寸信息     
  82.         //获取比例大小     
  83.         int wRatio = (int)Math.ceil(op.outWidth/DISPLAY_WIDTH);    
  84.         int hRatio = (int)Math.ceil(op.outHeight/DISPLAY_HEIGHT);    
  85.         //如果超出指定大小,则缩小相应的比例     
  86.         if(wRatio > 1 && hRatio > 1){    
  87.             if(wRatio > hRatio){    
  88.                 op.inSampleSize = wRatio;    
  89.             }else{    
  90.                 op.inSampleSize = hRatio;    
  91.             }    
  92.         }    
  93.         op.inJustDecodeBounds = false;    
  94.         bmp = BitmapFactory.decodeFile(path, op);    
  95.         return bmp;    
  96.     }  
  97. }  
main.xml:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="fill_parent"  
  4.     android:layout_height="fill_parent"  
  5.     android:orientation="vertical" >  
  6.   
  7.     <ImageButton  
  8.         android:id="@+id/image_view"  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content" />  
  11.   
  12.     <TextView  
  13.         android:id="@+id/view_name"  
  14.         android:layout_width="fill_parent"  
  15.         android:layout_height="wrap_content" />  
  16.   
  17. </LinearLayout>  
没有更多推荐了,返回首页