我正在尝试使用Square中的Picasso从URL中提取jpg,然后附加到EditText。 Picasso的原因在于它在实现中非常轻量级。可以看出我使用占位符ImageView,毕加索将从提供的URL导入图像,然后我将ImageView转换为Drawable。 ImageGetter也是如此。但是,当使用下面的配置时,我收到空指针错误。 (注意,当简单地使用应用程序资源中的drawable代替下面的'drawImage'变量时,此配置有效,但我正在尝试扩展它以从URL中提取资源)。
这里有什么不合适的地方吗?或者更有效的方法来做到这一点?
附加到EditText的方法:
public void appendToMessageHistory(String username, String message) {
if (username != null && message != null) {
ImageView image = new ImageView(getApplicationContext());
Picasso.with(getBaseContext()).load("http://localhost:3000/uploads/campaign/image/2/2.jpg").into(image);
Drawable drawImage = image.getDrawable();
messageHistoryText.append(Html.fromHtml("<b>" + username + ":"
+ "</b>" + "<br>"));
messageHistoryText.append(Html.fromHtml(message + "<hr>" + "<br>")
+ System.getProperty("line.separator") + "");
messageHistoryText.append(Html.fromHtml("<img src = '"
+ drawImage + "'/>",
imageGetter, null));
}
}
ImageGetter:
ImageGetter imageGetter = new ImageGetter() {
@Override
public Drawable getDrawable(String source) {
ImageView image = new ImageView(getApplicationContext());
Picasso.with(getBaseContext()).load("http://localhost:3000/uploads/campaign/image/2/2.jpg").into(image);
Drawable drawImage = image.getDrawable();
drawImage.setBounds(0, 0, drawImage.getIntrinsicHeight(), drawImage.getIntrinsicWidth());
return drawImage;
}
};
答案 0 :(得分:14)
你有点想念毕加索。您可以在inTo方法中设置一个匿名的Target类,并将位图设置为您拥有的任何对象:
Picasso.with(getBaseContext()).load("your url").into(new Target() {
@Override
public void onPrepareLoad(Drawable arg0) {
}
@Override
public void onBitmapLoaded(Bitmap bitmap, LoadedFrom arg1) {
// TODO Create your drawable from bitmap and append where you like.
}
@Override
public void onBitmapFailed(Drawable arg0) {
}
});
修改强> 所以你就是这样做的:
public void appendToMessageHistory(String username, String message) {
if (username != null && message != null) {
ImageView image = new ImageView(getApplicationContext());
Picasso.with(getBaseContext()).load("image url").into(new Target() {
@Override
public void onPrepareLoad(Drawable arg0) {
}
@Override
public void onBitmapLoaded(Bitmap bitmap, LoadedFrom arg1) {
Drawable drawImage = new BitmapDrawable(getBaseContext().getResources(),bitmap);
messageHistoryText.append(Html.fromHtml("<b>" + username + ":"
+ "</b>" + "<br>"));
messageHistoryText.append(Html.fromHtml(message + "<hr>" + "<br>")
+ System.getProperty("line.separator") + "");
messageHistoryText.append(Html.fromHtml("<img src = '"
+ drawImage + "'/>",
imageGetter, null));
}
@Override
public void onBitmapFailed(Drawable arg0) {
}
});
}
}