android获取网络图片

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

资源描述:

关于android获取网络图片主要是把网络图片的数据流读入到内存中然后用
1.Bitmap bitMap = BitmapFactory.decodeByteArray(data, 0, length); 
方法来将图片流传化为bitmap类型 这样才能用到
1.imageView.setImageBitmap(bitMap); 
来进行转化
在获取bitmap时候出现null 
错误代码:
byte[] data = GetImageForNet.getImage(path); 
int length = data.length; 
Bitmap bitMap = BitmapFactory.decodeByteArray(data, 0, length); 
imageView.setImageBitmap(bitMap); 
下面是 GetImageForNet.getImage()方法的代码清单
public static byte[] getImage(String path) throws Exception { 
URL url = new URL(path); 
HttpURLConnection httpURLconnection = (HttpURLConnection)url.openConnection(); 
httpURLconnection.setRequestMethod("GET"); 
httpURLconnection.setReadTimeout(6*1000); 
InputStream in = null; 
byte[] b = new byte[1024]; 
int len = -1; 
if (httpURLconnection.getResponseCode() == 200) { 
in = httpURLconnection.getInputStream(); 
in.read(b); 
in.close(); 
return b; 

return null; 

看起来没有问题 获取网络图片输入流,填充二进制数组,返回二进制数组,然后使用 Bitmap bitMap = BitmapFactory.decodeByteArray(data, 0, length); data就是返回的二进制数组
获取bitMap 看起来没有问题,可是bitMap就是为null!
BitmapFactory.decodeByteArray方法中所需要的data不一定是传统意义上的字节数组,查看android api,最后发现BitmapFactory.decodeByteArray所需要的data字节数组并不是想象中的数组!而是把输入流传化为字节内存输出流的字节数组格式
正确代码:
try { 
byte[] data = GetImageForNet.getImage(path); 
String d = new String(data); 
// File file = new File("1.jpg"); 
//OutputStream out = new FileOutputStream(file); 
//out.write(data); 
//out.close(); 
int length = data.length; 
Bitmap bitMap = BitmapFactory.decodeByteArray(data, 0, length); 
imageView.setImageBitmap(bitMap); 
//imageView.seti 
} catch (Exception e) { 
Log.i(TAG, e.toString()); 
Toast.makeText(DataActivity.this, "获取图片失败", 1).show(); 

下面是改进后的 GetImageForNet.getImage()方法的代码清单
public static byte[] getImage(String path) throws Exception { 
URL url = new URL(path); 
HttpURLConnection httpURLconnection = (HttpURLConnection)url.openConnection(); 
httpURLconnection.setRequestMethod("GET"); 
httpURLconnection.setReadTimeout(6*1000); 
InputStream in = null; 
byte[] b = new byte[1024]; 
int len = -1; 
if (httpURLconnection.getResponseCode() == 200) { 
in = httpURLconnection.getInputStream(); 
byte[] result = readStream(in); 
in.close(); 
return result; 


return null; 


public static byte[] readStream(InputStream in) throws Exception{ 
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); 
byte[] buffer = new byte[1024]; 
int len = -1; 
while((len = in.read(buffer)) != -1) { 
outputStream.write(buffer, 0, len); 

outputStream.close(); 
in.close(); 
return outputStream.toByteArray(); 
}


-------------------------------------------------------------------------------------------------------------------
android写入数据库、读取sqlite中的图片

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class AndroidTestActivity extends Activity {
    /** Called when the activity is first created. */
 
 private Button btn;
 
 private SQLiteDatabase db = null;
 
 private ImageView imageView;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        /**
         * getWritableDatabase()和getReadableDatabase()方法都可以获取一个用于操作数据库的SQLiteDatabase实例。
         * 但getWritableDatabase() 方法以读写方式打开数据库,一旦数据库的磁盘空间满了,数据库就只能读而不能写,
         * 倘若使用getWritableDatabase()打开数据库就会出错。getReadableDatabase()方法先以读写方式打开数据库,
         * 如果数据库的磁盘空间满了,就会打开失败,当打开失败后会继续尝试以只读方式打开数据库。
         */
        DBHelper helper = new DBHelper(AndroidTestActivity.this, "mysql1.txt");
  db = helper.getWritableDatabase();

  
        imageView=(ImageView)findViewById(R.id.imgView);
        btn=(Button)findViewById(R.id.button1);
        btn.setOnClickListener(
          
          new Button.OnClickListener()
          {
           public void onClick(View v)
           {
            String fileName="mysql.db";
               AssetManager assets = getAssets();
               try {
                InputStream is=assets.open(fileName);
                
                Log.v("is.length",  is.available()+"");
                
                FileOutputStream fos=new FileOutputStream(Environment.getDataDirectory()+ "/data/com.xujie.test/databases/" + "mysql1.txt");
                
                byte[]bytes=getInput(is);
                
//                int b=0;
                
//                while((b=is.read())!=-1)
//                {
//                 fos.write(b);
//                }
                fos.write(bytes);

        /**
         * 将数据流关闭
         */
                
             fos.flush();
          fos.close();        
          is.close();
          
               } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
      }
               
            Cursor cursor= get_equipment_by_id("3");
            
            while(cursor.moveToNext())
            {
             Bitmap bitmap=getIconFromCursor(cursor, cursor.getColumnIndex("icon"));

                Drawable drawable=new BitmapDrawable(bitmap);
                
                imageView.setImageDrawable(drawable);
            }
           }
          }
        );
    }
    
    
    public Bitmap getIconFromCursor(Cursor c, int iconIndex) { 
     byte[] data = c.getBlob(iconIndex); 
     try {

      Log.v("BitmapFactory.decodeByteArray.length000:", "BitmapFactory.decodeByteArray.length");
      Log.v("BitmapFactory.decodeByteArray.length:", BitmapFactory.decodeByteArray(data, 0, data.length).getWidth()+"");
      Log.v("BitmapFactory.decodeByteArray.length111:", "BitmapFactory.decodeByteArray.length");
      
     return BitmapFactory.decodeByteArray(data, 0, data.length); 
     } catch (Exception e) { 
     return null; 
     }
    }

    public byte[] getInput(InputStream is) throws IOException
 {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  byte[] b = new byte[1024];
  int len = 0;

  while ((len = is.read(b, 0, 1024)) != -1) 
  {
   baos.write(b, 0, len);
   baos.flush();
  }
  return baos.toByteArray();
 }
    
 /**
  * @name    get_equipment_by_id
  * @desc     设备列表
  * @author   liwang
  * @date    2011-12-28
  * @param   String type 设备类型
  * @return   Cursor
  */
 public Cursor get_equipment_by_id(String id)
 {
  return db.query("equipments", null, "id=?", new String[]{id} ,null, null, null);
 }
    class DBHelper extends SQLiteOpenHelper
 {

  public DBHelper(Context context, String name, CursorFactory factory, int version)
  {
   super(context, name, factory, version);
   // TODO Auto-generated constructor stub
  }
  public DBHelper(Context context, String name)
  {
   super(context, name, null, 1);
  }
  @Override
  public void onCreate(SQLiteDatabase db)
  {
   // TODO Auto-generated method stub
  }

  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
  {
   // TODO Auto-generated method stub
  }
 }
}

转载于:https://my.oschina.net/u/1423612/blog/291707

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/264617.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

gitlab备份及恢复

gitlab备份步骤 https://blog.csdn.net/qq_31666147/article/details/79844107 gitlab版本 下载地址 https://mirrors.tuna.tsinghua.edu.cn/gitlab-ce/yum/el7/ gitlab-ce-10.4.4-ce.0.el7.x86_64.rpm 备份恢复gitlib版本必须相同 转载于:https://www.cnblogs.com/mutong1228…

WSS Alert(邮件提醒) 定制

项目需要&#xff0c;研究了一下WSS的Alert定制。 定制有两种方法: (方法1)修改模板文件 默认模板是12\TEMPLATE\XML\alerttemplates.xml,将这个模板复制一份修改,然后用stsadm命令添加模板: STSADM -o updatealerttemplates -url <http://urlname> -filename <your w…

windows log日志分割_如何将日志记录到 Windows事件日志 中

每当出现一些未捕获异常时&#xff0c;操作系统都会将异常信息写入到 Windows 事件日志 中&#xff0c;可以通过 Windows 事件查看器 查看&#xff0c;如下图&#xff1a; 这篇文章将会讨论如何使用编程的方式将日志记录到 Windows 事件日志 中。 安装 EventLog 要想在 .NET Co…

偷窃转基因玉米种子引发中美打农业官司

偷窃转基因玉米种子引发中美打农业官司 请看下面相片&#xff1a; 这张相片是孩子们与转基因玉米在一起的景象。转基因玉米颗粒饱满&#xff0c;孩子们的小手差点儿抓不住&#xff08;由于玉米棒子非常粗&#xff09;。广大农民喜欢这样的抗虫、耐药并且产量高的农作物&#xf…

SQL Server : 禁止在SQL Server中生成用户实例

一、打开SQL工具&#xff0c;右键点服务器&#xff0c;新建查询 二、输入如下查询&#xff1a;exec sp_configure user instances enabled, 1 三、在查询中再运行&#xff1a;Reconfigure 四、然后重启SQL SERVER服务转载于:https://www.cnblogs.com/dushouke/arch…

mysql中视图的概念_MySql中的视图的概念及应用

视图的基本概念视图是从一个或几个基本表(或者视图)导出的表。它与基本表不同&#xff0c;是一个虚表。数据库只存放视图的定义&#xff0c;而不存放视图对应的数据&#xff0c;这些数据仍存放在原来的基本表中。所以基本表中的数据发生变化&#xff0c;从视图中查询出的数据也…

bzoj1190:[HNOI2007]梦幻岛宝珠

传送门 二进制分组优化背包 理解的差不多了&#xff0c;但是无法具体阐述&#xff0c;留坑 代码&#xff1a; #include<cstdio> #include<iostream> #include<algorithm> #include<vector> #include<cstring> using namespace std; void read(in…

JQuery常用的代码片段

2019独角兽企业重金招聘Python工程师标准>>> JQuery常用的代码片段 JQuery在当前众多网站开发中都有用到。他简易的操作以及对各个浏览器的兼容性&#xff0c;被广大的开发者一致看好。 下面是一些常用实用的 JQuery 代码片段。看看有没有需要收藏的吧&#xff1a; …

Lession 14 Do you speak Englist?

1过去完成时:1>动作发生在过去的过去;在过去动作完成,对过去产生影响,过去的时间壮语;2>原打算,但没实际的愿望;3>没听清,再次提问;had 过去分词2 New words and Expressions;amusing;experience;wave;lift;reply;language;journey;1>speak;speaker;say;说话内容;…

linux中mysql与eclipse_Linux下eclipse CDT及mysql安装,c++访问mysql数据库

5. 关于eclipse编译project由于程序中有#include所以需要在eclipse中加上对mysql.h的路径项目->属性->C/CBuild -> settings -> gcc c complier ->includes -> include paths添加两个路径&#xff1a;/usr/lib/mysql&#xff1b;/usr/include/mysql对于64位的…

linux环境配置

在安装linux之前首先要明白linux系统的功能特性&#xff0c;linux是多少位 的&#xff0c;对要使用的工具要有大体的了解&#xff0c;那样就不至于在之后的安装中耽误太多时间&#xff0c;比如安装的系统是32位的就要安装与之对应的工具。我们大体上了解一下linux能支持的又比较…

tomcat 启动速度慢背后的真相

1. tomcat 启动慢 在线上环境中&#xff0c;我们经常会遇到类似的问题&#xff0c;就是tomcat 启动比较慢&#xff0c;查看内存和cpu,io都是正常的&#xff0c;但是启动很慢&#xff0c;有的时候长达几分钟&#xff0c;这到底是什么原因导致的。 1.1 tomcat 获取随机值阻塞 ​ …

[导入]相片: 23853741.jpg

文章来源:http://img.blog.163.com/photo/NdAK9XEb2a-KOR7zpDWpAA/588564176302178421.jpg转载于:https://www.cnblogs.com/baiyirui/archive/2008/04/27/1173117.html

手摇泵PHP一32_节能手摇泵的制作方法

本实用新型属于液压动力装置技术领域&#xff0c;特指一种节能手摇泵。背景技术&#xff1a;如图1-2所示&#xff0c;目前&#xff0c;手摇泵采用分体式结构&#xff0c;比如&#xff0c;左横向出油通道和右横向出油通道是装配在泵体上的&#xff0c;由于零件较多&#xff0c;所…

2018-07-10 为Chrome和火狐浏览器编写扩展

由于扩展标准的逐渐一致, 现在同一扩展代码库已经有可能同时用于Chrome和火狐. 下面是一个简单的工具栏按钮和弹窗(尚无任何实际功能): 代码库地址: nobodxbodon/suan1 所有代码: manifest.json: {"manifest_version": 2,"name": "算一","v…

转基因大豆提高大豆油脂产量80%

2013年6月17日&#xff0c;农业部批准3种转基因大豆进口&#xff0c;可是&#xff0c;”准吃不准种“&#xff0c;请见《第一財经日报》相关报道。 据国外文献资料&#xff0c;“Soybean Oil: Genetic Approaches for Modification of Functionality and Total Content." …

掌握 ASP.NET 之路:自定义实体类简介 来源 :msdn

ADODB.RecordSet 和常常被遗忘的 MoveNext 的时代已经过去&#xff0c;取而代之的是 Microsoft ADO.NET 强大而又灵活的功能。我们的新武器就是 System.Data 名称空间&#xff0c;它的特点是具有速度极快的 DataReader 和功能丰富的 DataSet&#xff0c;而且打包在一个面向对象…

mysql数据库分表备份脚本_mysql 分库分表备份脚本

#!/bin/bashUSERroot #用户PASSWORD123456 #密码MYSQL_PATH127.0.0.1 #地址MYSQL_BIN/bin/mysqlMYSQL_DUMP_BIN/bin/mysqldumpMYSQL_CMD"${MYSQL_BIN} -u${USER} -p${PASSWORD} -h${MYSQL_PATH}"DATABASE($(${MYSQL_CMD} -e "show databases;"|egrep -v &q…

企业级 oracle11G r2 DataGuard 安装配置

企业级 oracle11G r2 DataGuard 安装配置安装环境IP地址与机器名 /etc/hosts# Do not remove the following line, or various programs# that require network functionality will fail.127.0.0.1 localhost.localdomain localhost::1 localhost6.local…

【LeetCode】390. 消除游戏

题目 给定一个从1 到 n 排序的整数列表。 首先&#xff0c;从左到右&#xff0c;从第一个数字开始&#xff0c;每隔一个数字进行删除&#xff0c;直到列表的末尾。 第二步&#xff0c;在剩下的数字中&#xff0c;从右到左&#xff0c;从倒数第一个数字开始&#xff0c;每隔一个…