APP、H5保存图片到本地

文章介绍了在APP和H5环境下如何保存图片到本地。APP端使用了plus.nativeObj.Bitmap和uni.saveImageToPhotosAlbum方法,而H5则借助html2canvas将HTML元素转换为图片并下载。此外,还涉及了图片上传到服务器的流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.APP保存图片到本地

	createImage() {
			// #ifdef H5
			this.$u.toast('H5暂不支持此功能');
			return;
			// #endif
			
			let pages = getCurrentPages();
			
			let page = pages[pages.length - 1];
			let ws = page.$getAppWebview();
			let bitmap = new plus.nativeObj.Bitmap('drawScreen');
			ws.draw(
				bitmap,
				() => {
					bitmap.save(
						'_doc/drawScreen.jpg',
						{
							overwrite: true
						},
						res => {
							
							this.picture = res.target;
							this.posterShow = true;
							bitmap.clear();
							this.$u.toast(this.posterShow,JSON.stringify(res));
						},
						error => {
							console.log(error);
							bitmap.clear();
						}
					);
				},
				error => {
					console.log(JSON.stringify(error));
					this.$u.toast(JSON.stringify(error));
				},
				{
					check: true,
					clip: {
						top: this.navigationBarHeight + this.statusBarHeight + 'px',
						left: this.left + 'px',
						width: this.windowWidth + 'px',
						height: this.windowHeight - this.statusBarHeight - this.navigationBarHeight + 'px'
					}
				}
			);
		},
downloadImage(callback) {
				// #ifdef H5
				this.$u.toast('H5暂不支持此功能')
				return;
				// #endif
				var _this = this;
				uni.saveImageToPhotosAlbum({
					filePath: _this.image_list[this.codeFlag],
					success(res) {
						console.log(res.path);
						if (callback) {
							uni.uploadFile({
								url: _this.siteBaseUrl + '/fileUploadAndDownload/upload',
								filePath: res.path,
								name: 'file',
								success: (uploadFileRes) => {
									let res = JSON.parse(uploadFileRes.data)
									_this.picture = res.data.file.url;
									callback();
								}
							});
						} else {
							_this.$u.toast('成功保存图片')
						}
					}
				})
			},

2.H5保存图片到本地

使用的html2canvas:配置型 | HTML2CANVAS 中文文档 (allenchinese.github.io)

import html2canvas from 'html2canvas';

		createImage() {
			html2canvas(document.querySelector("#imgimg"),{useCORS: true}).then(canvas => {
				const file = document.createElement("a");
				    file.style.display = "none";
				    file.href = canvas.toDataURL("image/jpg");
				    file.download = decodeURI('文件名');
				    document.body.appendChild(file);
				    file.click();
				    document.body.removeChild(file);
			});
		},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值