根据文件链接将文件下载到本地
public String downloadPic(String url){
String uuid= UUID.randomUUID().toString().replaceAll("-","");
String imgName=uuid;
String path1="D:\\testFile\\";
File tempFile = new File(path1);
if(!tempFile.exists()){
tempFile.mkdirs();
}
String path=path1+"\\"+imgName+".jpg";
try{
URL url1 = new URL(url);
DataInputStream dataInputStream = new DataInputStream(url1.openStream());
FileOutputStream fileOutputStream = new FileOutputStream(new File(path));
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = dataInputStream.read(buffer)) >0){
output.write(buffer,0,length);
}
fileOutputStream.write(output.toByteArray());
dataInputStream.close();
fileOutputStream.close();
}catch (MalformedURLException | FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return path;
}
将图片转换为base64
public String picToBase64(String imgFile){
InputStream inputStream = null;
byte[] data = null;
try {
inputStream = new FileInputStream(imgFile);
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
根据图片链接将图片转为base64
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import sun.misc.BASE64Encoder;
import java.io.*;
@Component
public class PicToBase64Utils {
@Autowired
private RestTemplate restTemplate;
public String PicToBase64(String url){
byte[] data = null;
try{
ResponseEntity<Resource> resourceResponseEntity = restTemplate.getForEntity(url, Resource.class);
InputStream inputStream = resourceResponseEntity.getBody().getInputStream();
data = new byte[inputStream.available()];
inputStream.read(data);
inputStream.close();
}catch (Exception e) {
e.printStackTrace();
}
BASE64Encoder encoder = new BASE64Encoder();
return encoder.encode(data);
}
}