package com.thfund.bigtree.StarCounselor.activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import com.bumptech.glide.Glide;
import com.thfund.bigtree.R;
import com.thfund.bigtree.base.BaseActivity;
import com.thfund.bigtree.utils.ToastUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class StarWeChatQRActivity extends BaseActivity implements View.OnClickListener {
private ImageView showImageView;//显示图片ImageView
private Button mSaveBtn;//保存图片按钮
private String imgURl;//图片的URL地址
private static final int SAVE_SUCCESS = 0;//保存图片成功
private static final int SAVE_FAILURE = 1;//保存图片失败
private static final int SAVE_BEGIN = 2;//开始保存图片
private Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SAVE_BEGIN:
ToastUtil.showMsg("开始保存图片...");
mSaveBtn.setClickable(false);
break;
case SAVE_SUCCESS:
ToastUtil.showMsg("图片保存成功,请到相册查找");
mSaveBtn.setClickable(true);
break;
case SAVE_FAILURE:
ToastUtil.showMsg("图片保存失败,请稍后再试...");
mSaveBtn.setClickable(true);
break;
}
}
};
/**
* 打开该Activity的一种静态方式
*
* @param context
* @param imgURl
*/
public static void startActivity(Context context, String imgURl) {
Intent intent = new Intent(context, StarWeChatQRActivity.class);
Bundle bundle = new Bundle();
bundle.putString("imgURl", imgURl);
intent.putExtras(bundle);
context.startActivity(intent);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_star_we_chat_qr);
initViews();
initData();
}
/**
* 初始化控件
*/
private void initViews() {
showImageView = (ImageView) findViewById(R.id.image_view);
mSaveBtn = (Button) findViewById(R.id.save_btn);
mSaveBtn.setOnClickListener(this);
}
/**
* 初始化数据
*/
private void initData() {
//我的ImageURL是上一级传参过来的
imgURl = getIntent().getStringExtra("imgURl");
//用Glide将图片加载出来
Glide.with(mContext).load(imgURl).fitCenter().crossFade().into(showImageView);
}
/**
* 点击事件处理
*
* @param v
*/
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.save_btn://保存图片
mSaveBtn.setClickable(false);//不可重复点击
//保存图片必须在子线程中操作,是耗时操作
new Thread(new Runnable() {
@Override
public void run() {
mHandler.obtainMessage(SAVE_BEGIN).sendToTarget();
Bitmap bp = returnBitMap(imgURl);
saveImageToPhotos(mContext, bp);
}
}).start();
break;
}
}
/**
* 保存二维码到本地相册
*/
private void saveImageToPhotos(Context context, Bitmap bmp) {
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory(), "Boohee");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
mHandler.obtainMessage(SAVE_FAILURE).sendToTarget();
return;
}
// 最后通知图库更新
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
context.sendBroadcast(intent);
mHandler.obtainMessage(SAVE_SUCCESS).sendToTarget();
}
/**
* 将URL转化成bitmap形式
*
* @param url
* @return bitmap type
*/
public final static Bitmap returnBitMap(String url) {
URL myFileUrl;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
HttpURLConnection conn;
conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 点击除了按钮的任何一个地方,finish掉
*
* @param event
* @return
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
finish();
break;
}
return super.onTouchEvent(event);
}
}
长按图片保存的弹框:
photoView.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View view) {
//弹出的“保存图片”的Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(GalleryActivity.this);
builder.setItems(new String[]{"保存","取消","编辑","收藏"}, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
switch (which){
case 0:
Toast.makeText(GalleryActivity.this,"0"+imagePath.get(position),Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(GalleryActivity.this,"1",Toast.LENGTH_SHORT).show();
break;
case 2:
Toast.makeText(GalleryActivity.this,"2",Toast.LENGTH_SHORT).show();
break;
case 3:
Toast.makeText(GalleryActivity.this,"3",Toast.LENGTH_SHORT).show();
break;
}
}
});
builder.show();
// Toast.makeText(GalleryActivity.this,""+imagePath.get(position),Toast.LENGTH_SHORT).show();
return false;
}
});
另一种保存图片的方式:
1.
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Base64;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.southsummer.goddessplan.R;
import com.southsummer.goddessplan.bean.NewsImage;
import com.southsummer.goddessplan.ui.adapters.PhotoViewPager;
import com.southsummer.goddessplan.ui.adapters.ViewPagerAdapter;
import com.southsummer.goddessplan.utils.AppUtils;
import com.southsummer.goddessplan.utils.CancelOrOkDialog;
import com.southsummer.goddessplan.utils.DonwloadSaveImg;
import com.southsummer.goddessplan.utils.ToastUtil;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
/**
* 查看图片
*/
public class PlusImageActivity extends AppCompatActivity implements ViewPager.OnPageChangeListener, View.OnClickListener {
private PhotoViewPager viewPager; //展示图片的ViewPager
private TextView positionTv; //图片的位置,第几张图片
// private ArrayList<String> imgList; //图片的数据源
private ArrayList<String> imgList;
private ArrayList<NewsImage> imgLists = new ArrayList<>(); //图片的数据源
private int mPosition; //第几张图片
private ViewPagerAdapter mAdapter;
private Context context;
private static final int SAVE_SUCCESS = 0;//保存图片成功
private static final int SAVE_FAILURE = 1;//保存图片失败
private static final int SAVE_BEGIN = 2;//开始保存图片
@SuppressLint("HandlerLeak")
private static Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SAVE_BEGIN:
ToastUtil.show(AppUtils.getContext().getString(R.string.start_saving));
break;
case SAVE_SUCCESS:
ToastUtil.show(AppUtils.getContext().getString(R.string.successful_preservation));
break;
case SAVE_FAILURE:
ToastUtil.show(AppUtils.getContext().getString(R.string.save_failed));
break;
}
}
};
private Bitmap bmp;
private ImageView back_iv;
private ImageView delete_iv;
private ImageView save_iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//去除标题栏
requestWindowFeature(Window.FEATURE_NO_TITLE);
//去除状态栏
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_plus_images);
imgList = (ArrayList<String>) getIntent().getSerializableExtra("img_list");
mPosition = getIntent().getIntExtra("position", 0);
context = AppUtils.getContext();
initView();
}
private void initView() {
viewPager = (PhotoViewPager) findViewById(R.id.viewPager);
positionTv = (TextView) findViewById(R.id.position_tv);
back_iv = (ImageView)findViewById(R.id.back_iv);
delete_iv = (ImageView)findViewById(R.id.delete_iv);
save_iv = (ImageView)findViewById(R.id.save_iv);
back_iv.setOnClickListener(this);
delete_iv.setOnClickListener(this);
save_iv.setOnClickListener(this);
viewPager.addOnPageChangeListener(this);
if(imgList!=null){
if(imgList.size()>0){
for (int i = 0; i < imgList.size(); i++) {
NewsImage newsImage = new NewsImage();
newsImage.setUrl(imgList.get(i));
imgLists.add(newsImage);
}
}
}
if (imgLists.size() > 0)
mAdapter = new ViewPagerAdapter(PlusImageActivity.this, imgLists);
viewPager.setAdapter(mAdapter);
positionTv.setText(mPosition + 1 + "/" + imgList.size());
viewPager.setCurrentItem(mPosition);
mAdapter.setItemClickListener(new ViewPagerAdapter.MyItemClickListener() {
@Override
public void onItemClick(int position) {
finish();
}
});
mAdapter.setItemLongClickListener(new ViewPagerAdapter.MyItemLongClickListener() {
@Override
public void onItemLongClick(int position) {
back_iv.setVisibility(View.VISIBLE);
delete_iv.setVisibility(View.GONE);
save_iv.setVisibility(View.VISIBLE);
}
});
}
/**
* 删除图片
*/
private void deletePic() {
CancelOrOkDialog dialog = new CancelOrOkDialog(this, context.getString(R.string.delete_confirmation_prompt)) {
@Override
public void ok() {
super.ok();
imgList.remove(mPosition); //从数据源移除删除的图片
setPosition();
dismiss();
}
};
dialog.show();
}
/**
* 保存图片
*/
private void savePic() {
CancelOrOkDialog dialog = new CancelOrOkDialog(this, context.getString(R.string.save_confirmation_prompt)) {
@Override
public void ok() {
super.ok();
// bmp = returnBitMap("http://img1.3lian.com/2015/w3/66/81.jpg");//保存String类型图片
// bmp = BitmapFactory.decodeResource(getResources(), R.drawable.ic_default_avatar);//保存int类型图片
// new Thread(new Runnable() {
// @Override
// public void run() {
// mHandler.obtainMessage(SAVE_BEGIN).sendToTarget();
// //保存
saveImageToGallery(PlusImageActivity.this, bmp);
// DonwloadSaveImg.donwloadImg(PlusImageActivity.this, imgLists.get(mPosition).getUrl());//iPath
// }
// }).start();
DonwloadSaveImg.donwloadImg(PlusImageActivity.this, imgLists.get(mPosition).getUrl());//iPath
dismiss();
}
};
dialog.show();
}
/**
* 保存图片
*
* @param context
* @param bmp
*/
public static void saveImageToGallery(Context context, Bitmap bmp) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
ToastUtil.show("保存失败,没有读写sd卡权限");
}
// 首先保存图片
File appDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath(), "Boohee");
if (!appDir.exists()) {
appDir.mkdir();
}
String fileName = System.currentTimeMillis() + ".jpg";
File file = new File(appDir, fileName);
try {
FileOutputStream fos = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 其次把文件插入到系统图库
try {
MediaStore.Images.Media.insertImage(context.getContentResolver(),
file.getAbsolutePath(), fileName, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
mHandler.obtainMessage(SAVE_FAILURE).sendToTarget();
return;
}
// 最后通知图库更新
context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse(file.getAbsolutePath())));
mHandler.obtainMessage(SAVE_SUCCESS).sendToTarget();
}
//设置当前位置
private void setPosition() {
if (imgList.size() == 0) {
finish();
return;
}
positionTv.setText(mPosition + 1 + "/" + imgList.size());
viewPager.setCurrentItem(mPosition);
mAdapter.notifyDataSetChanged();
}
//返回上一个页面
private void back() {
// Intent intent = getIntent();
// intent.putStringArrayListExtra("img_list", imgList);
// setResult(11, intent);
finish();
}
@Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
@Override
public void onPageSelected(int position) {
mPosition = position;
positionTv.setText(position + 1 + "/" + imgList.size());
}
@Override
public void onPageScrollStateChanged(int state) {
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.back_iv:
//返回
back();
break;
case R.id.delete_iv:
//删除图片
deletePic();
break;
case R.id.save_iv:
//保存图片
// DonwloadSaveImg.donwloadImg(PlusImageActivity.this, imgLists.get(mPosition).getUrl());//iPath
savePic();
break;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//按下了返回键
back();
return true;
}
return super.onKeyDown(keyCode, event);
}
/**
* 将URL转化成bitmap形式
*
* @param url
* @return bitmap type
*/
public final static Bitmap returnBitMap(String url) {
URL myFileUrl;
Bitmap bitmap = null;
try {
myFileUrl = new URL(url);
HttpURLConnection conn;
conn = (HttpURLConnection) myFileUrl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
public Bitmap stringToBitmap(String string) {
// 将字符串转换成Bitmap类型
Bitmap bitmap = null;
try {
byte[] bitmapArray;
bitmapArray = Base64.decode(string, Base64.DEFAULT);
bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0,
bitmapArray.length);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 点击除了按钮的任何一个地方,finish掉
*
* @param event
* @return
*/
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
finish();
break;
}
return super.onTouchEvent(event);
}
}
2.
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.widget.Toast;
import com.southsummer.goddessplan.R;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.UUID;
/**
* 保存图片到手机
*/
public class DonwloadSaveImg {
private static Context context;
private static String filePath;
private static Bitmap mBitmap;
private static String mSaveMessage = "Failure";
private final static String TAG = "PictureActivity";
private static ProgressDialog mSaveDialog = null;
public static void donwloadImg(Context contexts, String filePaths) {
context = contexts;
filePath = filePaths;
mSaveDialog = ProgressDialog.show(context, contexts.getString(R.string.save_picture), contexts.getString(R.string.start_saving), true);
new Thread(saveFileRunnable).start();
}
private static Runnable saveFileRunnable = new Runnable() {
@Override
public void run() {
try {
if (!TextUtils.isEmpty(filePath)) { //网络图片
// 对资源链接
URL url = new URL(filePath);
//打开输入流
InputStream inputStream = url.openStream();
//对网上资源进行下载转换位图图片
mBitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
}
saveFile(mBitmap);
mSaveMessage = AppUtils.getContext().getString(R.string.successful_preservation);
} catch (IOException e) {
mSaveMessage = AppUtils.getContext().getString(R.string.save_failed);
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
messageHandler.sendMessage(messageHandler.obtainMessage());
}
};
private static Handler messageHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
mSaveDialog.dismiss();
LogUtils.d(TAG, mSaveMessage);
Toast.makeText(context, mSaveMessage, Toast.LENGTH_SHORT).show();
}
};
/**
* 保存图片
* @param bm
* @throws IOException
*/
public static void saveFile(Bitmap bm ) throws IOException {
File dirFile = new File(Environment.getExternalStorageDirectory().getPath());
if (!dirFile.exists()) {
dirFile.mkdir();
}
String fileName = UUID.randomUUID().toString() + ".jpg";
File myCaptureFile = new File(Environment.getExternalStorageDirectory().getPath() + "/DCIM/Camera/" + fileName);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
//第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差 ,第三个参数:保存压缩后的数据的流
bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
//把图片保存后声明这个广播事件通知系统相册有新图片到来
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(myCaptureFile);
intent.setData(uri);
context.sendBroadcast(intent);
}
}