Bitmap基本概念:
- bitmap是Android系统中的图像处理的重要类之一;
- 通过bitmap我们可以获取到图片的相关信息;
- bitmap文件图像效果好就需要占用越大存储空间;
//查看图片
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends AppCompatActivity {
private EditText et_path;
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et_path = findViewById(R.id.et_path);
iv = findViewById(R.id.iv);
}
public void click(View v) {
new Thread() { //网络操作不能在UI线程中
public void run() {
try {
File file = new File(getCacheDir(), "test.png");
if (file.exists() && file.length() > 0) {
final Bitmap cacheBitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
runOnUiThread(new Runnable() { //UI操作要在UI线程中执行
@Override
public void run() {
iv.setImageBitmap(cacheBitmap);
}
});
}
String path = et_path.getText().toString().trim();
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
if (connection.getResponseCode() == 200) {
InputStream inputStream = connection.getInputStream();
FileOutputStream fileOutputStream = new FileOutputStream(file);
int len;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, len);
}
fileOutputStream.close();
inputStream.close();
final Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
runOnUiThread(new Runnable() { //UI操作要在UI线程中执行
@Override
public void run() {
iv.setImageBitmap(bitmap);
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}