之前是用glide加载然后在图片上画标注框是有问题的所以换了另外一种方式
思路:1.先把网络图片下载到本地之后画标注框 最后再压缩图片 及展示
上代码:
下载图片:
public class NetWorkUtils {
public static InputStream getImageInputStream(String imageUrl) {
URL url = null;
HttpURLConnection urlConnection = null;
try {
url = new URL(imageUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setConnectTimeout(2 * 1000);
return urlConnection.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
耗时操作
public class NetServiceTask extends AsyncTask<String, Void, Bitmap> implements Runnable {
private String address;
private URLPostHandler urlPostHandler = null;
private ProgressBar progressBar;
public NetServiceTask(String address, URLPostHandler urlPostHandler, ProgressBar progressBar) {
this.address = address;
this.urlPostHandler = urlPostHandler;
this.progressBar = progressBar;
}
@Override
protected Bitmap doInBackground(String... strings) {
InputStream imageInputStream = NetWorkUtils.getImageInputStream(strings[0]);
if (imageInputStream != null) {
return BitmapFactory.decodeStream(imageInputStream);
}
return null;
}
@Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
progressBar.setVisibility(View.GONE);
if (this.urlPostHandler != null && result != null) {
this.urlPostHandler.PostHandler(result);
}
}
@Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(View.VISIBLE);
}
@Override
public void run() {
execute(this.address);
}
public interface URLPostHandler {
void PostHandler(Bitmap bitmap);
}
}
最后调用:
NetServiceTask serviceTask = new NetServiceTask(defectDetail.fileLink, bitmap -> {
Bitmap copy = bitmap.copy(Bitmap.Config.ARGB_8888, true);
for (OrderDetailsResponse.DefectDetail.FileInfo fileInfo : defectDetail.photoUrl) {
int xmin = Math.round(fileInfo.xmin);
int xmax = Math.round(fileInfo.xmax);
int ymin = Math.round(fileInfo.ymin);
int ymax = Math.round(fileInfo.ymax);
if (null != copy) {
Rect rect = new Rect(xmin, ymax, xmax, ymin);
Canvas canvas = new Canvas(copy);
canvas.drawRect(rect, paint);
canvas.save();
canvas.restore();
}
}
saveImage(copy, imageFileName);
}, progressBar);
Thread thread = new Thread(serviceTask);
thread.start();
}
照片下载到本地目录代码:
private void saveImage(Bitmap image, String fileName) {
String saveImagePath = null;
boolean success = true;
if (!storageDir.exists()) {
success = storageDir.mkdirs();
}
if (success) {
File imageFile = new File(storageDir, fileName);
saveImagePath = imageFile.getAbsolutePath();
photoPath.add(saveImagePath);
try {
OutputStream fout = new FileOutputStream(imageFile);
image.compress(Bitmap.CompressFormat.JPEG, 100, fout);
fout.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Glide.with(mContext).load(saveImagePath).into(defectImage);
}
最后效果: