vue-copper跨域问题解决方案
方法一、保持图片和页面同一域名。
方法二、使用nginx代理,是图片和页面同一域名
方法三、如果图片服务允许跨域访问,可以在前端转成base64显示
function transImgToBase64(imgUrl){
// 一定要设置为let,不然图片不显示
let image = new Image()
// 解决跨域问题
image.setAttribute('crossOrigin', 'anonymous)');
image.src = `${imgUrl}?time=${new Date().valueOf()}`
image.onload = () => {
let canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
let context = canvas.getContext('2d');
context.drawImage(image, 0, 0, image.width, image.height);
let quality = 0.8;
imgUrl.value = canvas.toDataURL('image/jpeg', quality)
}
}
方法四、图片服务器不允许跨域访问,可以在后端进行base64转换后返回前端显示:
@GetMapping("/getImgBase64")
public AjaxResult getImgBase64(HttpServletResponse response) throws IOException
{
String imagePath = "https://xxx/xx.png";
URL url = new URL(imagePath);
BufferedImage bufferedImage = ImageIO.read(url);
FastByteArrayOutputStream byteArrayOutputStream = new FastByteArrayOutputStream();
ImageIO.write(bufferedImage,"png",byteArrayOutputStream);
byte[] imageByte = byteArrayOutputStream.toByteArray();
String base64Img =Base64.encode(imageByte);
AjaxResult ajax = AjaxResult.success();
ajax.put("img", "data:image/png;base64,"+base64Img);
注意:
base64编码的png图片数据前缀:data:image/png;base64,
base64编码的jpg图片数据前缀:data:image/jpg;base64,
base64编码的jpeg图片数据前缀:data:image/jpeg;base64