这里我想从String URL转换图像。虽然有一个包含图像的URL,但它返回null。我在下面分享了代码。
private byte[] convertImageToByteArray(String imgPath)
{
byte[] byteArray = null;
Bitmap bmp = BitmapFactory.decodeFile(imgPath);
if(bmp != null)
{
try {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//bmp.compress(Bitmap.CompressFormat.JPEG, 100, stream);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
try
{
stream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
else
{
try {
Bitmap bmpDefault = BitmapFactory.decodeResource(getResources(), R.drawable.na);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//bmpDefault.compress(Bitmap.CompressFormat.JPEG, 100, stream);
bmpDefault.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
}
catch (Exception e)
{
e.printStackTrace();
}
}
return byteArray;
}
控制流不是执行if块,而是进入else块,而BitmapFactory.decodeFile()总是返回null。哪里出错了?
答案 0 :(得分:3)
Ravindra的答案很有帮助,为了更好地利用图像尝试Picasso lib,令人兴奋。它还调整了大小/裁剪方法。
Picasso.with(getContext()).load("your url").into(new Target() {
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
//do what ever you want with your bitmap
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
}
});
答案 1 :(得分:2)
您可以使用此引用,它可能是helpfull。
注意: - 此功能进行网络连接,您应该在线程或AsyncTask中调用它。否则可能会抛出code = textwrap.dedent("""\
val NUM_SAMPLES = 100000;
val count = sc.parallelize(1 to NUM_SAMPLES).map { i =>
val x = Math.random();
val y = Math.random();
if (x*x + y*y < 1) 1 else 0
}.reduce(_ + _);
println(\"Pi is roughly \" + 4.0 * count / NUM_SAMPLES)
""")
data = { 'code': code }
r = requests.post(statements_url, data=json.dumps(data), headers=headers)
异常。
当函数返回Bitmap时,您必须等到线程执行完毕,请检查question。 它使用join()
我希望这会有所帮助。
答案 2 :(得分:1)
使用以下代码行: -
Bitmap bmImg;
AsyncTask<String, String, String> _Task = new AsyncTask<String, String, String>()
{
@Override
protected void onPreExecute()
{
String _imgURL = "**HERE IS YOUR URL OF THE IMAGE**";
}
@Override
protected String doInBackground(String... arg0)
{
HttpGet httpRequest = new HttpGet(URI.create(_imgURL));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufHttpEntity = new BufferedHttpEntity(entity);
bmImg = BitmapFactory.decodeStream(bufHttpEntity.getContent());
System.out.println("main url"+mainUrl);
httpRequest.abort();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(String result)
{
try
{
/////HERE USE YOURS BITMAP
**bmImg** is your bitmap , you can use it any where i your class
}
catch (Exception e)
{
e.printStackTrace();
}
}
};
_Task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);