android获取网络png格式图片
时间: 2023-11-30 15:02:59 浏览: 37
可以使用以下代码获取网络上的 PNG 格式图片:
```
try {
URL url = new URL("https://example.com/image.png");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (IOException e) {
// Handle exception
}
```
注意,这段代码应该在非 UI 线程中运行,否则会导致主线程阻塞。同时,由于网络请求可能会失败或超时,需要适当地处理异常情况。
相关问题
Android保存网络图片
要在Android上保存网络图片,可以使用以下代码:
```java
String imageUrl = "https://example.com/image.png";
String fileName = "myImage.png";
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), fileName);
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
}
```
在这个例子中,我们使用URL类打开一个URL连接,然后获取输入流并将其解码为位图。然后,我们创建一个名为“myImage.png”的文件并将位图压缩为PNG格式,最后将其写入文件中。请注意,我们需要获取WRITE_EXTERNAL_STORAGE权限才能将文件写入外部存储器。
android从excel中获取图片
在 Android 中,可以使用 Apache POI 库来读取 Excel 文件,并从中获取图片。以下是实现此操作的步骤:
1. 在 build.gradle 文件中添加 Apache POI 库的依赖:
```
implementation 'org.apache.poi:poi:4.1.2'
implementation 'org.apache.poi:poi-ooxml:4.1.2'
```
2. 使用 FileInputStream 读取 Excel 文件。
```java
FileInputStream fileInputStream = new FileInputStream(new File("path/to/excel/file.xlsx"));
```
3. 创建工作簿对象,并获取第一个工作表。
```java
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream);
XSSFSheet sheet = workbook.getSheetAt(0);
```
4. 遍历工作表中的每一行和每一列,查找包含图片的单元格。
```java
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == CellType.PICTURE) {
// 处理包含图片的单元格
}
}
}
```
5. 从包含图片的单元格中获取图片,并将其写入到文件中。
```java
XSSFPicture picture = (XSSFPicture) cell.getPicture(spreadsheet);
XSSFPictureData pictureData = picture.getPictureData();
byte[] pictureBytes = pictureData.getData();
FileOutputStream fileOutputStream = new FileOutputStream("path/to/output/image.png");
fileOutputStream.write(pictureBytes);
fileOutputStream.close();
```
请注意,以上代码仅适用于读取 XLSX 格式的 Excel 文件。如果要读取 XLS 格式的 Excel 文件,则需要使用 HSSFWorkbook 和 HSSFSheet 类。