Java Android从URL加载到位图
我有一个关于从网站加载图像的问题。我使用的代码是:Java Android从URL加载到位图,java,android,bitmap,Java,Android,Bitmap,我有一个关于从网站加载图像的问题。我使用的代码是: Display display = getWindowManager().getDefaultDisplay(); int width = display.getWidth(); int height = display.getHeight(); Bitmap bit=null; try { bit = BitmapFactory.decodeStream((InputStream)new URL("http://www.mac-wa
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Bitmap bit=null;
try {
bit = BitmapFactory.decodeStream((InputStream)new URL("http://www.mac-wallpapers.com/bulkupload/wallpapers/Apple%20Wallpapers/apple-black-logo-wallpaper.jpg").getContent());
} catch (Exception e) {}
Bitmap sc = Bitmap.createScaledBitmap(bit,width,height,true);
canvas.drawBitmap(sc,0,0,null);
但它总是返回空指针异常,程序就会崩溃。
URL是有效的,似乎对其他人都有效。
我使用的是2.3.1。试试这个:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
AQuery aq = new AQuery(getActivity());
aq.id(view.findViewById(R.id.image)).image(imageUrl, true, true, 0, 0,
new BitmapAjaxCallback() {
@Override
public void callback(String url, ImageView iv, Bitmap bm, AjaxStatus status){
iv.setImageBitmap(bm);
}
}.header("User-Agent", "android"));
private Bitmap getBitmap(String url)
{
File file=fileCache.getFile(url);
Bitmap bm = decodeFile(file);
if(bm!=null)
return bm;
try {
Bitmap bitmap=null;
URL ImageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)ImageUrl.openConnection();
conn.setConnectTimeout(50000);
conn.setReadTimeout(50000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(file);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(file);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
private Bitmap decodeFile(File file){
try {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(file),null,opt);
final int REQUIRED_SIZE=70;
int width_tmp=opt.outWidth, height_tmp=opt.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
BitmapFactory.Options opte = new BitmapFactory.Options();
opte.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(file), null, opte);
} catch (FileNotFoundException e) {}
return null;
}
非常快的方式,此方法工作非常快:
private Bitmap getBitmap(String url)
{
File f=fileCache.getFile(url);
//from SD cache
Bitmap b = decodeFile(f);
if(b!=null)
return b;
//from web
try {
Bitmap bitmap=null;
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
InputStream is=conn.getInputStream();
OutputStream os = new FileOutputStream(f);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(f);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
//decodes image and scales it to reduce memory consumption
private Bitmap decodeFile(File f){
try {
//decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE=70;
int width_tmp=o.outWidth, height_tmp=o.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
//decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {}
return null;
}
私有位图getBitmap(字符串url)
{
文件f=fileCache.getFile(url);
//从SD缓存
位图b=解码文件(f);
如果(b!=null)
返回b;
//从网络
试一试{
位图=空;
URL imageUrl=新URL(URL);
HttpURLConnection conn=(HttpURLConnection)imageUrl.openConnection();
连接设置连接超时(30000);
连接设置读取超时(30000);
conn.setInstanceFollowRedirects(真);
InputStream is=conn.getInputStream();
OutputStream os=新文件OutputStream(f);
Utils.CopyStream(is,os);
os.close();
位图=解码文件(f);
返回位图;
}捕获(例外情况除外){
例如printStackTrace();
返回null;
}
}
//对图像进行解码和缩放以减少内存消耗
私有位图解码文件(文件f){
试一试{
//解码图像大小
BitmapFactory.Options o=新的BitmapFactory.Options();
o、 inJustDecodeBounds=true;
解码流(新的FileInputStream(f),null,o);
//找到正确的刻度值。它应该是2的幂。
所需的最终int_尺寸=70;
内部宽度=o.向外宽度,高度=o.向外高度;
int标度=1;
while(true){
如果(width_tmp/2传递您的图像URL:
试试这个:
private Bitmap getBitmap(String url)
{
File file=fileCache.getFile(url);
Bitmap bm = decodeFile(file);
if(bm!=null)
return bm;
try {
Bitmap bitmap=null;
URL ImageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection)ImageUrl.openConnection();
conn.setConnectTimeout(50000);
conn.setReadTimeout(50000);
conn.setInstanceFollowRedirects(true);
InputStream is = conn.getInputStream();
OutputStream os = new FileOutputStream(file);
Utils.CopyStream(is, os);
os.close();
bitmap = decodeFile(file);
return bitmap;
} catch (Exception ex){
ex.printStackTrace();
return null;
}
}
private Bitmap decodeFile(File file){
try {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(file),null,opt);
final int REQUIRED_SIZE=70;
int width_tmp=opt.outWidth, height_tmp=opt.outHeight;
int scale=1;
while(true){
if(width_tmp/2<REQUIRED_SIZE || height_tmp/2<REQUIRED_SIZE)
break;
width_tmp/=2;
height_tmp/=2;
scale*=2;
}
BitmapFactory.Options opte = new BitmapFactory.Options();
opte.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(file), null, opte);
} catch (FileNotFoundException e) {}
return null;
}
我更喜欢这些:
从InputStream创建位图并返回它:
public static Bitmap downloadImage(String url) {
Bitmap bitmap = null;
InputStream stream = null;
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
try {
stream = getHttpConnection(url);
bitmap = BitmapFactory.decodeStream(stream, null, bmOptions);
stream.close();
}
catch (IOException e1) {
e1.printStackTrace();
System.out.println("downloadImage"+ e1.toString());
}
return bitmap;
}
// Makes HttpURLConnection and returns InputStream
public static InputStream getHttpConnection(String urlString) throws IOException {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
try {
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
}
}
catch (Exception ex) {
ex.printStackTrace();
System.out.println("downloadImage" + ex.toString());
}
return stream;
}
记住:
Android包括两个HTTP客户端:HttpURLConnection和ApacheHTTP客户端。
对于姜饼和更高版本,HttpURLConnection是最佳选择
从Android 3.x蜂巢或更高版本,您无法在UI线程上执行网络IO,执行此操作将引发Android.os.NetworkOnMainThreadException。您必须使用Asynctask,如下所示
图像位图的异步任务*/
私有类AsyncGettingBitmapFromUrl扩展AsyncTask{
@凌驾
受保护位图doInBackground(字符串…参数){
System.out.println(“doInBackground”);
位图=空;
位图=AppMethods.downloadImage(参数[0]);
返回位图;
}
@凌驾
受保护的void onPostExecute(位图){
System.out.println(“位图”+位图);
}
}
如果您使用或从url加载图像。您只需通过以下方式获取加载的位图: 毕加索的(当前版本
2.71828
)
Java代码
Picasso.get().load(imageUrl).into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
// loaded bitmap is here (bitmap)
}
@Override
public void onBitmapFailed(Drawable errorDrawable) { }
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {}
});
imageLoader.loadImage(imageUrl, new SimpleImageLoadingListener()
{
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
// loaded bitmap is here (loadedImage)
}
});
科特林代码
Picasso.get().load(url).into(object : com.squareup.picasso.Target {
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
// loaded bitmap is here (bitmap)
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {}
})
用于滑行检查 用于通用图像加载器
Java代码
imageLoader.loadImage(imageUrl, new SimpleImageLoadingListener()
{
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage)
{
// loaded bitmap is here (loadedImage)
}
});
按照这个方法在android中获取位图的url,只需传递这个图像的链接并获取位图
public static Bitmap getBitmapFromURL(String imgUrl) {
try {
URL url = new URL(imgUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
// Log exception
return null;
}
}
Glide.with(上下文)
.加载(“http://test.com/yourimage.jpg")
.asBitmap()//
.fitCenter()
.into(新的SimpleTarget(100100){
@凌驾
public void onResourceReady(位图、动画)
使用Glide库并在发布的工作线程中运行以下代码请尝试以下步骤
1) 在类或适配器中创建AsyncTask(如果要更改列表项映像)
2.b)对于活动和片段:
**Activity:**
ImageView imagview= (ImageView) findViewById(R.Id.imageview);
String src = (your image string);
new AsyncTaskLoadImage(imagview).execute(src);
**Fragment:**
ImageView imagview= (ImageView)view.findViewById(R.Id.imageview);
String src = (your image string);
new AsyncTaskLoadImage(imagview).execute(src);
3) 请运行应用程序并检查图像
快乐编码…:)如果您从位图加载URL而不使用AsyncTask,请在setContentView(R.layout.abc)之后写两行
若你们正在使用毕加索的图像,你们可以尝试下面的方法
public static Bitmap getImageBitmapFromURL(Context context, String imageUrl){
Bitmap imageBitmap = null;
try {
imageBitmap = new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
try {
int targetHeight = 200;
int targetWidth = 200;
return Picasso.with(context).load(String.valueOf(imageUrl))
//.resize(targetWidth, targetHeight)
.placeholder(R.drawable.raw_image)
.error(R.drawable.raw_error_image)
.get();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
}
return imageBitmap;
}
公共静态位图getImageBitmapFromURL(上下文上下文,字符串imageUrl){
位图imageBitmap=null;
试一试{
imageBitmap=新建异步任务(){
@凌驾
受保护位图doInBackground(无效…参数){
试一试{
int targetHeight=200;
int targetWidth=200;
返回Picasso.with(context.load)(String.valueOf(imageUrl))
//.调整大小(targetWidth、targetLight)
.占位符(R.drawable.raw_图像)
.error(R.drawable.raw\u error\u图像)
.get();
}捕获(IOE异常){
e、 printStackTrace();
}
返回null;
}
}.execute().get();
}捕捉(中断异常e){
e、 printStackTrace();
}
返回图像位图;
}
如果您正在使用和Kotlin
Glide.with(this)
.asBitmap()
.load("https://...")
.addListener(object : RequestListener<Bitmap> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Bitmap>?,
isFirstResource: Boolean
): Boolean {
Toast.makeText(this@MainActivity, "failed: " + e?.printStackTrace(), Toast.LENGTH_SHORT).show()
return false
}
override fun onResourceReady(
resource: Bitmap?,
model: Any?,
target: Target<Bitmap>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
//image is ready, you can get bitmap here
var bitmap = resource
return false
}
})
.into(imageView)
Glide.with(这个)
.asBitmap()
.加载(“https://...")
.addListener(对象:RequestListener{
覆盖加载失败(
e:例外情况?,
型号:有吗?,
目标:目标?,
isFirstResource:布尔值
):布尔值{
Toast.makeText(this@MainActivity,“失败:”+e?.printStackTrace(),Toast.LENGTH\u SHORT.show()
返回错误
}
覆盖资源就绪(
资源:位图?,
型号:有吗?,
目标:目标?,
数据源:数据源?,
isFirstResource:布尔值
):布尔值{
//图像已准备好,您可以在此处获取位图
var位图=资源
返回错误
}
})
public class AsyncTaskLoadImage extends AsyncTask<String, String, Bitmap> {
private final static String TAG = "AsyncTaskLoadImage";
private ImageView imageView;
public AsyncTaskLoadImage(ImageView imageView) {
this.imageView = imageView;
}
@Override
protected Bitmap doInBackground(String... params) {
Bitmap bitmap = null;
try {
URL url = new URL(params[0]);
bitmap = BitmapFactory.decodeStream((InputStream) url.getContent());
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
try {
int width, height;
height = bitmap.getHeight();
width = bitmap.getWidth();
Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas c = new Canvas(bmpGrayscale);
Paint paint = new Paint();
ColorMatrix cm = new ColorMatrix();
cm.setSaturation(0);
ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
paint.setColorFilter(f);
c.drawBitmap(bitmap, 0, 0, paint);
imageView.setImageBitmap(bmpGrayscale);
} catch (Exception e) {
e.printStackTrace();
}
}
}
String src = current.getProductImage();
new AsyncTaskLoadImage(holder.icon).execute(src);
**Activity:**
ImageView imagview= (ImageView) findViewById(R.Id.imageview);
String src = (your image string);
new AsyncTaskLoadImage(imagview).execute(src);
**Fragment:**
ImageView imagview= (ImageView)view.findViewById(R.Id.imageview);
String src = (your image string);
new AsyncTaskLoadImage(imagview).execute(src);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch(IOException e) {
System.out.println(e);
}
public static Bitmap getImageBitmapFromURL(Context context, String imageUrl){
Bitmap imageBitmap = null;
try {
imageBitmap = new AsyncTask<Void, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(Void... params) {
try {
int targetHeight = 200;
int targetWidth = 200;
return Picasso.with(context).load(String.valueOf(imageUrl))
//.resize(targetWidth, targetHeight)
.placeholder(R.drawable.raw_image)
.error(R.drawable.raw_error_image)
.get();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
}
return imageBitmap;
}
Glide.with(this)
.asBitmap()
.load("https://...")
.addListener(object : RequestListener<Bitmap> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Bitmap>?,
isFirstResource: Boolean
): Boolean {
Toast.makeText(this@MainActivity, "failed: " + e?.printStackTrace(), Toast.LENGTH_SHORT).show()
return false
}
override fun onResourceReady(
resource: Bitmap?,
model: Any?,
target: Target<Bitmap>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
//image is ready, you can get bitmap here
var bitmap = resource
return false
}
})
.into(imageView)
@Override
protected void onCreate() {
super.onCreate();
//setNotificationBadge();
if (android.os.Build.VERSION.SDK_INT >= 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
}
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
Menu menu = bottomNavigationView.getMenu();
MenuItem userImage = menu.findItem(R.id.navigation_download);
userImage.setTitle("Login");
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
URL url = new URL("https://rukminim1.flixcart.com/image/832/832/jmux18w0/mobile/b/g/n/mi-redmi-6-mzb6387in-original-imaf9z8eheryfbsu.jpeg?q=70");
Bitmap myBitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
Log.e("keshav", "Bitmap " + myBitmap);
userImage.setIcon(new BitmapDrawable(getResources(), myBitmap));
} catch (IOException e) {
Log.e("keshav", "Exception " + e.getMessage());
}
}
});
suspend fun bitmapToByteArray(url: String) = withContext(Dispatchers.IO) {
MutableLiveData<Lce<ContentResult.ContentBitmap>>().apply {
postValue(Lce.Loading())
postValue(Lce.Content(ContentResult.ContentBitmap(
ByteArrayOutputStream().apply {
try {
BitmapFactory.decodeStream(URL(url).openConnection().apply {
doInput = true
connect()
}.getInputStream())
} catch (e: IOException) {
postValue(Lce.Error(ContentResult.ContentBitmap(ByteArray(0), "bitmapToByteArray error or null - ${e.localizedMessage}")))
null
}?.compress(CompressFormat.JPEG, BITMAP_COMPRESSION_QUALITY, this)
}.toByteArray(), "")))
}
}
//Calls bitmapToByteArray from the Repository
private fun bitmapToByteArray(url: String) = liveData {
emitSource(switchMap(repository.bitmapToByteArray(url)) { lce ->
when (lce) {
is Lce.Loading -> liveData {}
is Lce.Content -> liveData {
emit(Event(ContentResult.ContentBitmap(lce.packet.image, lce.packet.errorMessage)))
}
is Lce.Error -> liveData {
Crashlytics.log(Log.WARN, LOG_TAG,
"bitmapToByteArray error or null - ${lce.packet.errorMessage}")
}
}
})
}
fun ByteArray.byteArrayToBitmap(context: Context) =
run {
BitmapFactory.decodeByteArray(this, BITMAP_OFFSET, size).run {
if (this != null) this
// In case the Bitmap loaded was empty or there is an error I have a default Bitmap to return.
else AppCompatResources.getDrawable(context, ic_coinverse_48dp)?.toBitmap()
}
}
fun getBitmap(url : String?) : Bitmap? {
var bmp : Bitmap ? = null
Picasso.get().load(url).into(object : com.squareup.picasso.Target {
override fun onBitmapLoaded(bitmap: Bitmap?, from: Picasso.LoadedFrom?) {
bmp = bitmap
}
override fun onPrepareLoad(placeHolderDrawable: Drawable?) {}
override fun onBitmapFailed(e: Exception?, errorDrawable: Drawable?) {}
})
return bmp
}
private class AsyncTaskRunner extends AsyncTask<String, String, String> {
String Imageurl;
public AsyncTaskRunner(String Imageurl) {
this.Imageurl = Imageurl;
}
@Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(Imageurl);
thumbnail_r = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e) {
}
return null;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
imgDummy.setImageBitmap(thumbnail_r);
UtilityMethods.tuchOn(relProgress);
}
}
AsyncTaskRunner asyncTaskRunner = new AsyncTaskRunner(uploadsModel.getImages());
asyncTaskRunner.execute();
private var image: Bitmap? = null
private fun getBitmapFromURL(src: String?) {
CoroutineScope(Job() + Dispatchers.IO).launch {
try {
val url = URL(src)
val bitMap = BitmapFactory.decodeStream(url.openConnection().getInputStream())
image = Bitmap.createScaledBitmap(bitMap, 100, 100, true)
} catch (e: IOException) {
// Log exception
}
}
}