首页 > 系统 > Android > 正文

Android长按保存图片

2019-11-07 23:10:57
字体:
来源:转载
供稿:网友

在做一个商城类App时,有个需求就是长按图片保存到本地图库,图片展示在了ViewPage和WebView中(图文混排展示商品详情的).所以分两部分来做,第一部分保存图片的方法,第二部分长按WebView时识别出来按的是哪一张图片,因为有很多张图片。

保存图片的方法,两个参数,一个上下文环境和一个图片的url,使用时只需要把这两个参数获取到传递过来即可:

public class SavePicByUrlUtils {PRivate static HttpURLConnection urlConnection;public static void getBitmap(Context context, String imageUrl) { try { URL url1 = new URL(imageUrl); urlConnection = (HttpURLConnection) url1.openConnection(); urlConnection.setReadTimeout(5000); urlConnection.setConnectTimeout(5000); urlConnection.setRequestMethod("GET"); if (urlConnection.getResponseCode() == 200) { InputStream inputStream = urlConnection.getInputStream(); Bitmap bitmap = BitmapFactory.decodeStream(inputStream); //将图片保存到本地 savePic2Phone(context, bitmap); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { urlConnection.disconnect(); }}private static void savePic2Phone(Context context, Bitmap bmp) { // 首先保存图片 File appDir = new File(Environment.getExternalStorageDirectory(), "dsh"); 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(); } // 最后通知图库更新 context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + Environment.getExternalStorageDirectory()))); ToastUtils.showMyToastMethod((ProDetailActivity) context, "图片保存成功");}}

获取WebView中很多图片中按着的那一张的方法:

WebView webView = (WebView) v; HitTestResult hitTestResult = webView.getHitTestResult(); if (webView.getHitTestResult().IMAGE_TYPE == hitTestResult.getType() || hitTestResult.getType() == HitTestResult.SRC_IMAGE_ANCHOR_TYPE) { //获取到长按着的那张图片的url String url = hitTestResult.getExtra();}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表