Android实现QQ图片说说照片选择效果

本文实例为大家分享了Android实现QQ图片说说照片选择的具体代码,供大家参考,具体内容如下

效果展示

布局文件

布局是很简单的,一个GridView,直接上布局:

layout/activity_add_photo.xml

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

 <RelativeLayout
  android:layout_width="match_parent"
  android:layout_height="60dp"
  android:background="#00BB9C">

  <TextView
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_centerInParent="true"
   android:text="写动态"
   android:textAppearance="?android:attr/textAppearanceLarge"
   android:textColor="@android:color/white" />

  <TextView
   android:id="@+id/send"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:layout_alignParentRight="true"
   android:layout_centerVertical="true"
   android:layout_marginRight="10dp"
   android:text="发送"
   android:textAppearance="?android:attr/textAppearanceLarge"
   android:textColor="@android:color/white" />

 </RelativeLayout>

 <LinearLayout
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_margin="16dp"
  android:orientation="vertical">

  <EditText
   android:layout_width="match_parent"
   android:layout_height="100dp"
   android:enabled="false"
   android:focusable="false"
   android:gravity="top"
   android:hint="分享您的那点新鲜事儿..."
   android:maxLines="5" />

  <LinearLayout
   android:layout_width="match_parent"
   android:layout_height="match_parent"
   android:padding="5dp">

   <GridView
    android:id="@+id/gridview"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:numColumns="4" />

  </LinearLayout>  

 </LinearLayout>

</LinearLayout>

layout/activity_add_photo_gv_items.xml 使用了自定义的view使得布局为正方形

<?xml version="1.0" encoding="utf-8"?>
<com.shenhua.tabhostdemo.selectimg.SquareRelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content">

 <ImageView
  android:id="@+id/main_gridView_item_photo"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:layout_centerInParent="true"
  android:contentDescription="@null"
  android:padding="5dp"
  android:scaleType="fitXY" />

 <CheckBox
  android:id="@+id/main_gridView_item_cb"
  android:layout_width="20dp"
  android:layout_height="20dp"
  android:layout_alignParentEnd="true"
  android:layout_alignParentRight="true"
  android:layout_alignParentTop="true"
  android:layout_margin="2dp"
  android:background="@drawable/ic_delete"
  android:backgroundTint="#00BB9C"
  android:button="@null" />

</com.shenhua.tabhostdemo.selectimg.SquareRelativeLayout>

代码实现

SquareRelativeLayout.java:

package com.shenhua.tabhostdemo.selectimg;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.RelativeLayout;

/**
 * 自定义方形布局
 * Created by Shenhua on 4/25/2016.
 */
public class SquareRelativeLayout extends RelativeLayout {
 public SquareRelativeLayout(Context context, AttributeSet attrs, int defStyle) {
  super(context, attrs, defStyle);
 }

 public SquareRelativeLayout(Context context, AttributeSet attrs) {
  super(context, attrs);
 }

 public SquareRelativeLayout(Context context) {
  super(context);
 }

 @Override
 protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  setMeasuredDimension(getDefaultSize(0, widthMeasureSpec), getDefaultSize(0, heightMeasureSpec));
  int childWidthSize = getMeasuredWidth();
  widthMeasureSpec = MeasureSpec.makeMeasureSpec(childWidthSize, MeasureSpec.EXACTLY);
  heightMeasureSpec = widthMeasureSpec;
  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
 }
}

UploadPhotoActivity.java: 主Activity

package com.shenhua.tabhostdemo.selectimg;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.shenhua.tabhostdemo.R;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by shenhua on 4/25/2016.
 */
public class UploadPhotoActivity extends AppCompatActivity {

 private static final int IMG_COUNT = 8;
 private static final String IMG_ADD_TAG = "a";
 private GridView gridView;
 private GVAdapter adapter;
 private TextView textView;
 private ImageView img;
 private List<String> list;

 @Override
 protected void onCreate(@Nullable Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_add_photo);
  gridView = (GridView) findViewById(R.id.gridview);
  textView = (TextView) findViewById(R.id.send);
  textView.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    System.out.println("发送:" + Integer.toString(list.size() - 1));
    upLoad();
   }
  });
  initData();
 }

 private void upLoad() {
  Bitmap bitmap;
  Bitmap bmpCompressed;
  for (int i = 0; i < list.size() - 1; i++) {
   bitmap = BitmapFactory.decodeFile(list.get(i));
   bmpCompressed = Bitmap.createScaledBitmap(bitmap, 640, 480, true);
   ByteArrayOutputStream bos = new ByteArrayOutputStream();
   bmpCompressed.compress(Bitmap.CompressFormat.JPEG, 100, bos);
   byte[] data = bos.toByteArray();
   System.out.println(data);
  }

 }

 private void initData() {
  if (list == null) {
   list = new ArrayList<>();
   list.add(IMG_ADD_TAG);
  }
  adapter = new GVAdapter();
  gridView.setAdapter(adapter);
  gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    if (list.get(position).equals(IMG_ADD_TAG)) {
     if (list.size() < IMG_COUNT) {
      Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
      startActivityForResult(i, 0);
     } else
      Toast.makeText(UploadPhotoActivity.this, "最多只能选择7张照片!", Toast.LENGTH_SHORT).show();
    }
   }
  });
  refreshAdapter();
 }

 private void refreshAdapter() {
  if (list == null) {
   list = new ArrayList<>();
  }
  if (adapter == null) {
   adapter = new GVAdapter();
  }
  adapter.notifyDataSetChanged();
 }

 private class GVAdapter extends BaseAdapter {

  @Override
  public int getCount() {
   return list.size();
  }

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

  @Override
  public long getItemId(int position) {
   return 0;
  }

  @Override
  public View getView(final int position, View convertView, ViewGroup parent) {
   final ViewHolder holder;
   if (convertView == null) {
    convertView = LayoutInflater.from(getApplication()).inflate(R.layout.activity_add_photo_gv_items, parent, false);
    holder = new ViewHolder();
    holder.imageView = (ImageView) convertView.findViewById(R.id.main_gridView_item_photo);
    holder.checkBox = (CheckBox) convertView.findViewById(R.id.main_gridView_item_cb);
    convertView.setTag(holder);
   } else {
    holder = (ViewHolder) convertView.getTag();
   }
   String s = list.get(position);
   if (!s.equals(IMG_ADD_TAG)) {
    holder.checkBox.setVisibility(View.VISIBLE);
    holder.imageView.setImageBitmap(ImageTool.createImageThumbnail(s));
   } else {
    holder.checkBox.setVisibility(View.GONE);
    holder.imageView.setImageResource(R.mipmap.ic_photo_upload);
   }
   holder.checkBox.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
     list.remove(position);
     refreshAdapter();
    }
   });
   return convertView;
  }

  private class ViewHolder {
   ImageView imageView;
   CheckBox checkBox;
  }

 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  if (data == null) {
   System.out.println("data null");
   return;
  }
  if (requestCode == 0) {
   final Uri uri = data.getData();
   String path = ImageTool.getImageAbsolutePath(this, uri);
   System.out.println(path);
   if (list.size() == IMG_COUNT) {
    removeItem();
    refreshAdapter();
    return;
   }
   removeItem();
   list.add(path);
   list.add(IMG_ADD_TAG);
   refreshAdapter();
  }
 }

 private void removeItem() {
  if (list.size() != IMG_COUNT) {
   if (list.size() != 0) {
    list.remove(list.size() - 1);
   }
  }
 }

}

ImageTool.java: 图片工具类

package com.shenhua.tabhostdemo.selectimg;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

/**
 * Created by shenhua on 4/26/2016.
 */
public class ImageTool {

 /**
  * 获取图片的绝对路径,需要添加用户权限
  */
 @TargetApi(19)
 public static String getImageAbsolutePath(Activity context, Uri imageUri) {
  if (context == null || imageUri == null)
   return null;
  if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
   if (isExternalStorageDocument(imageUri)) {
    String docId = DocumentsContract.getDocumentId(imageUri);
    String[] split = docId.split(":");
    String type = split[0];
    if ("primary".equalsIgnoreCase(type)) {
     return Environment.getExternalStorageDirectory() + "/" + split[1];
    }
   } else if (isDownloadsDocument(imageUri)) {
    String id = DocumentsContract.getDocumentId(imageUri);
    Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
    return getDataColumn(context, contentUri, null, null);
   } else if (isMediaDocument(imageUri)) {
    String docId = DocumentsContract.getDocumentId(imageUri);
    String[] split = docId.split(":");
    String type = split[0];
    Uri contentUri = null;
    if ("image".equals(type)) {
     contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    } else if ("video".equals(type)) {
     contentUri = null;//不获取视频
    } else if ("audio".equals(type)) {
     contentUri = null;//不获取音频
    }
    String selection = MediaStore.Images.Media._ID + "=?";
    String[] selectionArgs = new String[]{split[1]};
    return getDataColumn(context, contentUri, selection, selectionArgs);
   }
  } // MediaStore (and general)
  else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
   if (isGooglePhotosUri(imageUri))
    return imageUri.getLastPathSegment();
   return getDataColumn(context, imageUri, null, null);
  }
  // File
  else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
   return imageUri.getPath();
  }
  return null;
 }

 public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
  Cursor cursor = null;
  String column = MediaStore.Images.Media.DATA;
  String[] projection = {column};
  try {
   cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
   if (cursor != null && cursor.moveToFirst()) {
    int index = cursor.getColumnIndexOrThrow(column);
    return cursor.getString(index);
   }
  } finally {
   if (cursor != null)
    cursor.close();
  }
  return null;
 }

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is ExternalStorageProvider.
  */
 public static boolean isExternalStorageDocument(Uri uri) {
  return "com.android.externalstorage.documents".equals(uri.getAuthority());
 }

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

 /**
  * @param uri The Uri to check.
  * @return Whether the Uri authority is MediaProvider.
  */
 public 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 Google Photos.
  */
 public static boolean isGooglePhotosUri(Uri uri) {
  return "com.google.android.apps.photos.content".equals(uri.getAuthority());
 }

 /**
  * 创建图片缩略图
  *
  * @param filePath
  * @return
  */
 public static Bitmap createImageThumbnail(String filePath) {
  Bitmap bitmap = null;
  BitmapFactory.Options opts = new BitmapFactory.Options();
  opts.inJustDecodeBounds = true;
  BitmapFactory.decodeFile(filePath, opts);
  opts.inSampleSize = computeSampleSize(opts, -1, 128 * 128);
  opts.inJustDecodeBounds = false;
  try {
   bitmap = BitmapFactory.decodeFile(filePath, opts);
  } catch (Exception e) {
   // TODO: handle exception
  }
  return bitmap;
 }

 public static int computeSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
  int initialSize = computeInitialSampleSize(options, minSideLength, maxNumOfPixels);
  int roundedSize;
  if (initialSize <= 8) {
   roundedSize = 1;
   while (roundedSize < initialSize) {
    roundedSize <<= 1;
   }
  } else {
   roundedSize = (initialSize + 7) / 8 * 8;
  }
  return roundedSize;
 }

 private static int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
  double w = options.outWidth;
  double h = options.outHeight;
  int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
  int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h / minSideLength));
  if (upperBound < lowerBound) {
   // return the larger one when there is no overlapping zone.
   return lowerBound;
  }
  if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
   return 1;
  } else if (minSideLength == -1) {
   return lowerBound;
  } else {
   return upperBound;
  }
 }
}

因为 Android4.4以上版本获得的图片URI是com.xxxxx的,因此需要在工具类里做判断,否则得不到图片的绝对地址。

工具类参考了别人的一篇博客,忘了留博客地址了,请原博主谅解。

最后需要加上一个权限:

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • android中写一个内部类来选择文件夹中指定的图片类型实例说明

    复制代码 代码如下: /**本类是用来选择文件夹中是.jpg类型的图片*/ private class JpgFileFilter implements FilenameFilter{ @Override public boolean accept(File dir, String filename) { // TODO Auto-generated method stub return filename.endsWith(".jpg"); } }

  • Android实现本地图片选择及预览缩放效果

    在做项目时经常会遇到选择本地图片的需求,以前都是懒得写直接调用系统方法来选择图片,但是这样并不能实现多选效果,最近又遇到了,所以还是写一个demo好了,以后也方便使用.还是首先来看看效果: 显示的图片使用RecyclerView实现的,利用Glide来加载:下面弹出的图片文件夹效果是采用PopupWindow实现,这里比采用PopupWindow更方便,弹出显示的左边图片是这个文件夹里的第一张图片:选中的图片可以进行预览,使用网上一个大神写的来实现的:至于图片的获取是用ContentProvid

  • Android选择图片或拍照图片上传到服务器

    最近要搞一个项目,需要上传相册和拍照的图片,不负所望,终于完成了!  不过需要说明一下,其实网上很多教程拍照的图片,都是缩略图不是很清晰,所以需要在调用照相机的时候,事先生成一个地址,用于标识拍照的图片URI 具体上传代码: 1.选择图片和上传界面,包括上传完成和异常的回调监听 package com.spring.sky.image.upload; import java.util.HashMap; import java.util.Map; import android.app.Activi

  • Android拍照或从图库选择图片并裁剪

    今天看<第一行代码>上面关于拍照和从相册选取图片那一部分,发现始终出不来效果,所以搜索其他资料学习一下相关知识,写一个简单的Demo. 一. 拍照选择图片 1.使用隐式Intent启动相机 //构建隐式Intent Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); //调用系统相机 startActivityForResult(intent, 1); 2.处理相机拍照返回的结果 //用户点击了取消 if(data == n

  • Android实现拍照、选择图片并裁剪图片功能

    一. 实现拍照.选择图片并裁剪图片效果 按照之前博客的风格,首先看下实现效果. 二. uCrop项目应用 想起之前看到的Yalantis/uCrop效果比较绚,但是研究源码之后发现在定制界面方面还是有一点的限制,于是在它的基础上做了修改Android-Crop,把定制界面独立出来,让用户去自由设置.下图为使用Android-Crop实现的模仿微信选择图片并裁剪Demo. 三. 实现思路 比较简单的选择设备图片裁剪,并将裁剪后的图片保存到指定路径: 调用系统拍照,将拍照图片保存在SD卡,然后裁剪图

  • android完美实现 拍照 选择图片 剪裁等代码分享

    前言,版本兼容问题主要是由于4.4以前和4.4以后的Uri的格式不同所造成的错误 1.拍照 和选择图片   ①选择图片 intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, GALLERY_REQUEST_CODE); ②拍照 intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE)

  • Android仿微信照片选择器实现预览查看图片

    好了下面进入正题,我们先看一下实现效果吧: 下面来介绍一下代码: 本思路就是: 1.先到手机中扫描jpeg和png的图片 2.获取导图片的路径和图片的父路径名也就是文件夹名 3.将图片路径和文件夹名分别添加导数据源中 4.数据源有了就是显示了,文件夹显示是利用的popwindow,而图片显示则是GridView 看一下具体代码: 首先开启一个线程去扫描图片 /** * 利用ContentProvider扫描手机中的图片,此方法在运行在子线程中 完成图片的扫描,最终获得jpg最多的那个文件夹 */

  • 分享实现Android图片选择的两种方式

    Android选择图片的两种方式: 第一种:单张选取 通过隐式启动activity,跳转到相册选择一张返回结果 关键代码如下: 发送请求: private static final int PICTURE = 10086; //requestcode Intent intent = new Intent(); if (Build.VERSION.SDK_INT < 19) {//因为Android SDK在4.4版本后图片action变化了 所以在这里先判断一下 intent.setAction

  • 浅谈谈Android 图片选择器

    ImageSelector 简介 Android自定义相册,实现了拍照.图片选择(单选/多选).ImageLoader无绑定 任由开发者选择 https://github.com/YancyYe/ImageSelector Demo Download Apk 更新内容 UI重改 所有功能可配置 解决OOM情况 图片手动选择 支持汉语和英语 截图展示 使用说明 步骤一: 通过Gradle抓取 dependencies { compile 'com.yancy.imageselector:image

  • Android仿微信选择图片和拍照功能

    本文实例为大家分享了 Android微信选择图片的具体代码,和微信拍照功能,供大家参考,具体内容如下 1.Android6.0系统,对于权限的使用都是需要申请,选择图片和拍照需要申请Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE这两个权限. if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageM

随机推荐