CompressUtils.uts 8.7 KB
Newer Older
1
import {
DCloud-yyl's avatar
DCloud-yyl 已提交
2 3
	CompressImageSuccess, CompressImageOptions,
	CompressVideoOptions, CompressVideoSuccess
4 5
} from "../../interface.uts"
import {
DCloud-yyl's avatar
DCloud-yyl 已提交
6 7
	UniError_CompressVideo,UniError_CompressImage,
	MediaErrorImpl
8 9 10 11 12 13 14 15 16 17 18 19 20
} from "../../unierror.uts"
import TextUtils from 'android.text.TextUtils';
import File from 'java.io.File';
import BitmapFactory from 'android.graphics.BitmapFactory';
import Bitmap from 'android.graphics.Bitmap';
import Matrix from 'android.graphics.Matrix';
import FileOutputStream from 'java.io.FileOutputStream';
import ExifInterface from 'io.dcloud.uts.util.ExifInterface';
import Field from 'java.lang.reflect.Field';
import MediaTranscoder from 'io.dcloud.uts.androidtranscoder.MediaTranscoder';
import MediaFormatStrategyPresets from 'io.dcloud.uts.androidtranscoder.format.MediaFormatStrategyPresets';
import Listener from 'io.dcloud.uts.androidtranscoder.MediaTranscoder.Listener';

DCloud-yyl's avatar
DCloud-yyl 已提交
21
const mediaCachePath = UTSAndroid.getAppCachePath()+"uni-media/"
22 23 24 25
// export function threadCompress() {
// }
export function transcodeImage(options : CompressImageOptions) {
	if (options.src.length == 0) {
DCloud-yyl's avatar
DCloud-yyl 已提交
26 27 28
		let error = new MediaErrorImpl(1101003, UniError_CompressImage);
		options.fail?.(error)
		options.complete?.(error)
29 30 31 32 33 34
		return
	}
	let compressOption = new CompressOptions()
	compressOption.src = UTSAndroid.convert2AbsFullPath(options.src)
	let srcFile = new File(compressOption.src)
	if (!srcFile.exists()) {
DCloud-yyl's avatar
DCloud-yyl 已提交
35 36 37
		let error = new MediaErrorImpl(1101003, UniError_CompressImage);
		options.fail?.(error)
		options.complete?.(error)
38 39 40 41 42 43 44 45 46 47 48
		return
	}
	if (options.quality != null && options.quality! > 0) {
		compressOption.quality = options.quality!
	}
	if (options.rotate != null && options.rotate! >= 0) {
		compressOption.rotate = options.rotate!
	}
	var widthStr = ""
	var heightStr = ""
	if (options.compressedWidth != null) {
DCloud-yyl's avatar
DCloud-yyl 已提交
49
		widthStr = options.compressedWidth.toString();
50 51 52 53
	} else {
		widthStr = TextUtils.isEmpty(options.width) ? "auto" : options.width!
	}
	if (options.compressedHeight != null) {
DCloud-yyl's avatar
DCloud-yyl 已提交
54
		heightStr = options.compressedHeight.toString();
55 56 57
	} else {
		heightStr = TextUtils.isEmpty(options.height) ? "auto" : options.height!
	}
DCloud-yyl's avatar
DCloud-yyl 已提交
58
	getHeightAndWidth(compressOption, widthStr, heightStr);
59 60 61 62 63 64 65 66 67 68 69 70 71
	let bitmapOptions = new BitmapFactory.Options()
	bitmapOptions.inJustDecodeBounds = false;
	if (srcFile.length() > 1500000) {
		bitmapOptions.inSampleSize = 2
	} else {
		bitmapOptions.inSampleSize = 1
	}
	var srcBitmap : Bitmap | null = null
	try {
		srcBitmap = BitmapFactory.decodeFile(compressOption.src, bitmapOptions)
	} catch (e) {
	}
	if (srcBitmap == null) {
DCloud-yyl's avatar
DCloud-yyl 已提交
72 73 74
		let error = new MediaErrorImpl(1101009, UniError_CompressImage);
		options.fail?.(error)
		options.complete?.(error)
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
		return
	}

	if (compressOption.isZoom && compressOption.width > 0 && compressOption.height > 0) {
		let matrix = new Matrix()
		let scaleW = compressOption.width / srcBitmap.getWidth()
		let scaleH = compressOption.height / srcBitmap.getHeight()
		matrix.setScale(scaleW.toFloat(), scaleH.toFloat())
		srcBitmap = Bitmap.createBitmap(srcBitmap!, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, false)
	}
	if (compressOption.rotate > 0) {
		let matrix = new Matrix()
		matrix.postRotate(compressOption.rotate.toFloat())
		srcBitmap = Bitmap.createBitmap(srcBitmap!, 0, 0, srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, false)
	}
	// 保存
DCloud-yyl's avatar
DCloud-yyl 已提交
91
	let destPath = mediaCachePath + System.currentTimeMillis() + ".jpg"
92 93 94 95 96 97 98 99 100 101 102 103
	let destFile = new File(destPath)
	if (!destFile.getParentFile().exists()) {
		destFile.getParentFile().mkdirs()
	}
	try {
		let fos = new FileOutputStream(destFile)
		srcBitmap!.compress(Bitmap.CompressFormat.JPEG, compressOption.quality.toInt(), fos);
		fos.close()
		if (!srcBitmap!.isRecycled()) {
			srcBitmap!.recycle()
		}
		saveExif(options.src, destPath)
DCloud-yyl's avatar
DCloud-yyl 已提交
104
		let success : CompressImageSuccess = { "tempFilePath": "file://" + destPath }
105 106 107
		options.success?.(success)
		options.complete?.(success)
	} catch (ex) {
DCloud-yyl's avatar
DCloud-yyl 已提交
108 109 110
		let error = new MediaErrorImpl(1101009, UniError_CompressImage);
		options.fail?.(error)
		options.complete?.(error)
111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175
	}
}

function saveExif(oldFilePath : string, newFilePath : string) {
	try {
		let oldExif = new ExifInterface(oldFilePath);
		let newExif = new ExifInterface(newFilePath);
		let cls = oldExif.javaClass;
		let fields = cls.getFields();
		fields.forEach((field : Field) => {
			let fieldName = field.getName();
			if (!TextUtils.isEmpty(fieldName) && fieldName.startsWith("TAG")) {
				var o = field.get(cls);
				if (o != null) {
					var fieldValue = o.toString();
					var attribute = oldExif.getAttribute(fieldValue);
					if (attribute != null) {
						newExif.setAttribute(fieldValue, attribute);
					}
				}
			}
		})
		// for (Field field : fields) {

		// }
		newExif.saveAttributes();
	} catch (e) {

	}
}

function getHeightAndWidth(compressOption : CompressOptions, widthStr : string, heightStr : string) {
	let bopt = new BitmapFactory.Options()
	bopt.inJustDecodeBounds = true
	BitmapFactory.decodeFile(compressOption.src, bopt)
	let bitmapWidth = bopt.outWidth
	let bitmapHeight = bopt.outHeight
	if (bitmapHeight <= 0 || bitmapWidth <= 0) {
		return
	}
	if (widthStr.toLowerCase() == "auto" && heightStr.toLowerCase() == "auto") {
		compressOption.isZoom = false
		compressOption.width = bitmapWidth
		compressOption.height = bitmapHeight
	} else if (widthStr.toLowerCase() == "auto") {
		compressOption.isZoom = true
		compressOption.height = str2Float(heightStr, bitmapHeight, bitmapHeight)
		compressOption.width = bitmapWidth * compressOption.height / bitmapHeight
	} else if (heightStr.toLowerCase() == "auto") {
		compressOption.isZoom = true
		compressOption.width = str2Float(widthStr, bitmapWidth, bitmapWidth)
		compressOption.height = bitmapHeight * compressOption.width / bitmapWidth
	} else {
		compressOption.isZoom = true
		compressOption.width = str2Float(widthStr, bitmapWidth, bitmapWidth)
		compressOption.height = str2Float(heightStr, bitmapHeight, bitmapHeight)
	}
}

function str2Float(valuestr : string, realValue : number, defValue : number) : number {
	if (TextUtils.isEmpty(valuestr)) {
		return defValue
	}
	valuestr = valuestr.toLowerCase()
	if (valuestr.endsWith("px")) {
DCloud-yyl's avatar
DCloud-yyl 已提交
176
		valuestr = valuestr.substring(0, valuestr.length - 2);
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206
	}
	try {
		return Integer.parseInt(valuestr)
	} catch (e) {
		if (valuestr.endsWith("%")) {
			valuestr = valuestr.substring(0, valuestr.length - 1)
		}
		try {
			return realValue * Integer.parseInt(valuestr) / 100
		} catch (e) {
			return defValue
		}
	}
}

class CompressOptions {
	src : string = ""
	dst : string = ""
	format : string = ""
	quality : number = 80
	width : number = 0
	height : number = 0
	rotate : number = 0
	isZoom : boolean = false
}

export function transcodeVideo(options : CompressVideoOptions) {
	let inPath = UTSAndroid.convert2AbsFullPath(options.src)
	let inFile = new File(inPath)
	if (!inFile.exists()) {
DCloud-yyl's avatar
DCloud-yyl 已提交
207 208 209
		let error = new MediaErrorImpl(1101003, UniError_CompressVideo);
		options.fail?.(error)
		options.complete?.(error)
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
		return
	}
	var compressLevel = 1
	switch (options.quality) {
		case "low":
			compressLevel = 3
			break
		case "medium":
			compressLevel = 2
			break
		default:
			compressLevel = 1
			break
	}

	var resolution = options.resolution?.toDouble();

	if (resolution == null) {
		resolution = 1.0
	} else if (resolution! > 1 || resolution! <= 0) {
		resolution = 1.0
	}
DCloud-yyl's avatar
DCloud-yyl 已提交
232
	let outPath = mediaCachePath + "compress_video_" + System.currentTimeMillis() + ".mp4";
233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
	let outFile = new File(outPath)
	if (!outFile.getParentFile().exists()) {
		outFile.getParentFile().mkdirs()
	}

	MediaTranscoder.getInstance().transcodeVideo(inPath, outPath, MediaFormatStrategyPresets.createAndroid720pStrategy(compressLevel, resolution!), new MediaTranscoderListener(inPath, outPath, options))
}

class MediaTranscoderListener implements Listener {
	inPath : string
	outPath : string
	options : CompressVideoOptions
	constructor(inPath : string, outPath : string, options : CompressVideoOptions) {
		this.inPath = inPath
		this.outPath = outPath;
		this.options = options
	}
	override onTranscodeProgress(progress : Double) {

	}

	override onTranscodeCompleted() {
		let outFile = new File(this.outPath)
		if (outFile.exists()) {
DCloud-yyl's avatar
DCloud-yyl 已提交
257
			let success : CompressVideoSuccess = {
258
				tempFilePath: "file://" + this.outPath,
DCloud-yyl's avatar
DCloud-yyl 已提交
259
				size: outFile.length() / 1024
260 261 262 263
			}
			this.options.success?.(success)
			this.options.complete?.(success)
		} else {
DCloud-yyl's avatar
DCloud-yyl 已提交
264
			let error = new MediaErrorImpl(1101004, UniError_CompressVideo);
265 266 267 268 269 270
			this.options.fail?.(error)
			this.options.complete?.(error)
		}
	}

	override onTranscodeCanceled() {
DCloud-yyl's avatar
DCloud-yyl 已提交
271
		let error = new MediaErrorImpl(1101004, UniError_CompressVideo);
272 273 274 275 276
		this.options.fail?.(error)
		this.options.complete?.(error)
	}

	override onTranscodeFailed(exception : Exception) {
DCloud-yyl's avatar
DCloud-yyl 已提交
277
		let error = new MediaErrorImpl(1101010, UniError_CompressVideo);
278 279 280 281
		this.options.fail?.(error)
		this.options.complete?.(error)
	}
}