Android截图

Android中截图很好实现,从开发文档中,可以看到View有一个接口getDrawingCache(),这个接口可以获取View在调用这个接口时的位图图像Bitmap。

截图是抓取View在某一个时刻的图像,包含了addView到这个View的所有子View的图像,比如在截取Activity时,图像是不会包含浮现在activity上方的对话框的

下面的代码是截取图像并且经过http post接口上传到服务器的例子,截图并上传的核心代码如下:

Screenshot.java

package com.example.scrmdemo;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;

public class Screenshot {

	public static Bitmap takeScreenshotForView(View view) {
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap tempBit = view.getDrawingCache();
		Rect frame = new Rect();
		view.getWindowVisibleDisplayFrame(frame);
		int width = view.getWidth();
		int height = view.getHeight();
		Bitmap bitmap = Bitmap.createBitmap(tempBit, 0, 0, width, height);
		view.destroyDrawingCache();
		return bitmap;
	}

	public static Bitmap takeScreenshotForActivity(Activity activity) {
		View view = activity.getWindow().getDecorView();
		view.setDrawingCacheEnabled(true);
		view.buildDrawingCache();
		Bitmap tempBit = view.getDrawingCache();
		Rect frame = new Rect();
		view.getWindowVisibleDisplayFrame(frame);
		int statusBarHeight = frame.top;
		int width = view.getWidth();
		int height = view.getHeight();
		Bitmap bitmap = Bitmap.createBitmap(tempBit, 0, statusBarHeight, width,
				height - statusBarHeight);
		view.destroyDrawingCache();
		return bitmap;
	}

	public static Drawable BitmapToDrawable(Bitmap bitmap) {
		@SuppressWarnings("deprecation")
		BitmapDrawable bd = new BitmapDrawable(bitmap);
		Drawable drawable = (Drawable) bd;
		return drawable;
	}

	public static boolean savePic(Bitmap bitmap, String fileName) {
		try {
			File file = new File(fileName);
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			FileOutputStream fos = null;
			fos = new FileOutputStream(file);
			bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
			fos.flush();
			fos.close();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}
	}

	public static byte[] getBytes(Bitmap bitmap) {
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
		try {
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return out.toByteArray();
	}

	interface ISharePicCallBack {
		public final static int SHARE_OK = 1;
		public final static int SHARE_NOTOK = 2;

		public void shareResult(int resultCode, String output);
	}

	public static void share(final String urlStr, final Bitmap bitmap,
			final ISharePicCallBack callBack) {
		new Thread() {
			public void run() {
				try {
					URL url = new URL(urlStr);
					HttpURLConnection httpConn = (HttpURLConnection) url
							.openConnection();
					httpConn.setDoOutput(true);
					httpConn.setDoInput(true);
					httpConn.setUseCaches(false);
					httpConn.setRequestMethod("POST");
					byte[] requestStringBytes = getBytes(bitmap);
					httpConn.setRequestProperty("Content-length", ""
							+ requestStringBytes.length);
					httpConn.setRequestProperty("Content-Type",
							"application/octet-stream");
					httpConn.setRequestProperty("Connection", "Keep-Alive");
					httpConn.setRequestProperty("Charset", "UTF-8");
					OutputStream outputStream = httpConn.getOutputStream();
					outputStream.write(requestStringBytes);
					outputStream.flush();
					outputStream.close();
					if (HttpURLConnection.HTTP_OK == httpConn.getResponseCode()) {
						StringBuffer sb = new StringBuffer();
						String readLine;
						BufferedReader responseReader;
						responseReader = new BufferedReader(
								new InputStreamReader(
										httpConn.getInputStream(), "UTF-8"));
						while ((readLine = responseReader.readLine()) != null) {
							sb.append(readLine).append("\n");
						}
						responseReader.close();
						callBack.shareResult(ISharePicCallBack.SHARE_OK,
								sb.toString());
					} else {
						callBack.shareResult(ISharePicCallBack.SHARE_NOTOK, ""
								+ httpConn.getResponseCode());
					}
				} catch (IOException e) {
					callBack.shareResult(ISharePicCallBack.SHARE_NOTOK, "");
					e.printStackTrace();
				}
			};
		}.start();
	}
}

使用本文件时,需要向Android工程的AndroidManifest.xml配置文件中添加两个权限:

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

Android截图

时间: 2024-10-05 13:53:00

Android截图的相关文章

Android截图命令screencap与视频录制命令screenrecord

Android截图命令screencap 查看帮助命令 [email protected] ~$ adb shell screencap -v screencap: invalid option -- v usage: screencap [-hp] [-d display-id] [FILENAME] -h: this message -p: save the file as a png. -d: specify the display id to capture, default 0. If

【Android测试】Android截图的深水区

◆版权声明:本文出自胖喵~的博客,转载必须注明出处. 转载请注明出处:http://www.cnblogs.com/by-dream/p/6113059.html 需求 这两天遇到这样一个事情,因为某测试任务,需要在操作过程中连续的截图,最终分析截图.之前同事用的工具兼容性特别的不好,需要root,并且只适配固定几个版本的机型,因此我决定自己实现一个.首先最先想到的就是使用Uiautomator 1中自带的API来截图. 我们看下Uiautomator 1.0中提供的截图相关的API是什么样子的

vlc android 截图和录制视频(vlc0.9.9)

1.下载编译vlc 0.9.9 参考https://wiki.videolan.org/AndroidCompile/ 我的系统是Ubuntu 14.04 64位 2.在项目根目录../android,打上补丁 git apply *.patch 3.在../android/vlc,打上补丁 4.重新编译即可 要截图和录制视频的时候 只要使用LibVLC.java中的下面接口 public boolean takeSnapShot(String file, int width, int heig

Android截图截取弹框AlertDialog

1:效果如图 2:权限 <uses-sdk android:minSdkVersion="21" android:targetSdkVersion="21" /> <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permissi

关于android截图的一些方法

这里只记录一些链接,对于我的需求,只需要, public static String createScreenShot(View v)     {        //测试截屏功能    SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd_HH-mm-ss",Locale.US);    String dirPath=Mapplication.SDPATH+Constants.QZ_PATH;    File dirFile=

Android截图&lt;包括Alertdiaog&gt;

1.使用的系统内部的截屏方法-- 2. public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity"; View view1; int x=1; private static final int REQUEST_MEDIA_PROJECTION = 1; private MediaProjectionManager projectionMana

Android截图命令screencap

查看帮助命令 [email protected] ~$ adb shell screencap -v screencap: invalid option -- v usage: screencap [-hp] [-d display-id] [FILENAME] -h: this message -p: save the file as a png. -d: specify the display id to capture, default 0. If FILENAME ends with .

android 截图,视频录制命令 screencap screenrecord screenshot

时间限制视频录制: screenrecord  --time-limit 20 /sdcard/demo.mp4 抓屏: screencap -p /sdcard/screen.png screenshot /sdcard/screen.png 视频录制命令screenrecord # screenrecord --help Usage: screenrecord [options] <filename> Records the device's display to a .mp4 file.

android 截图保存位置不在已选择的“SD卡”中

修改GlobalScreenshot.java的saveImageInBackgroundTask方法: String imageDir = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_PICTURES).getAbsolutePath(); 1.JB2修改为: String imageDir = StorageManager.getDefaultPath() + '/' + Environment.D