把view保存为图片的方法以及解决保存后图片背景变黑色的问题
来源:互联网 发布:计算机通信与网络 编辑:程序博客网 时间:2024/04/27 22:59
原文地址:http://blog.csdn.net/u011494050/article/details/38776913
public class MainActivity extends Activity {
ImageView imgView;@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imgView = (ImageView) findViewById(R.id.imageView);
imgView.setDrawingCacheEnabled(true);
// this is the important code :)
// Without it the view will have a dimension of 0,0 and the bitmap will be null
imgView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
imgView.layout(0, 0, imgView.getMeasuredWidth(), imgView.getMeasuredHeight());
Bitmap bitmap = Bitmap.createBitmap(imgView.getDrawingCache());
imgView.setDrawingCacheEnabled(false);
String strPath ="/testSaveView/"+UUID.randomUUID().toString()+".png";
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
{
File sdCardDir=Environment.getExternalStorageDirectory();
FileOutputStream fos = null;
try{
File file = new File(sdCardDir,strPath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
fos = new FileOutputStream(file);
//当指定压缩格式为PNG时保存下来的图片显示正常
bitmap.compress(CompressFormat.JPEG, 100, fos);
//当指定压缩格式为JPEG时保存下来的图片背景为黑色
// bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="centerInside"
android:src="@drawable/ic_launcher"/>
</LinearLayout>
需要注意两个问题:
一、调用getDrawingCache()前先要测量,否则的话得到的bitmap为null,这个我在OnCreate()、OnStart()、OnResume()方法里都试验过。
二、当调用bitmap.compress(CompressFormat.JPEG, 100, fos);保存为图片时发现图片背景为黑色,如下图:
这时只需要改成用png保存就可以了,bitmap.compress(CompressFormat.PNG, 100, fos);,如下图:
0 0
- 【android】把view保存为图片的方法以及解决保存后图片背景变黑色的问题
- 把view保存为图片的方法以及解决保存后图片背景变黑色的问题
- 关于图片下载后保存背景透明变黑色的问题
- 解决java压缩图片透明背景变黑色的问题
- MATLAB 保存图片变黑色
- 下载保存的图片背景由透明变为黑色问题解决
- matlab 保存出来的图片或pdf背景为黑色解决方案,验证
- 获取上传的图片并保存为缩略图,解决gif背景变黑问题
- 获取上传的图片并保存为缩略图,解决gif背景变黑问题
- 将View的内容保存为图片
- 解决thinkphp图片上传生成缩略图背景为黑色的问题
- 去掉图片转换后的黑色背景
- 保存图片的方法
- 将屏幕保存为图片的方法
- cocos2d-x中截屏的方法、保存图片,以及使用截屏作为背景实例
- 把 Rational Rose 的图表保存为图片文件
- opencv把视频的每一帧保存为图片
- 将ViEW保存为图片
- Linux NFS服务器的安装与配置
- 创建.a文件
- Ubuntu下修改环境变量的三种方法
- 高并发处理/服务器宕机处理
- Buy Tickets
- 把view保存为图片的方法以及解决保存后图片背景变黑色的问题
- python构建关键词共现矩阵
- MyBatis工作原理
- 国外讲解rest的好网址
- 欢迎使用CSDN-markdown编辑器
- Android Studio插件FindBugs的安装与使用
- c++第3次实验-定期存款
- 2012蓝桥杯试题第五题
- Spring注解@Component、@Repository、@Service、@Controller区别