掃二維碼與項目經理溝通
我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯網交流
想了解更多關于開源的內容,請訪問:

創(chuàng)新互聯建站專注于企業(yè)全網營銷推廣、網站重做改版、嵐山網站定制設計、自適應品牌網站建設、H5開發(fā)、成都做商城網站、集團公司官網建設、成都外貿網站建設、高端網站制作、響應式網頁設計等建站業(yè)務,價格優(yōu)惠性價比高,為嵐山等各大城市提供網站開發(fā)制作服務。
開源基礎軟件社區(qū)
https://ost.
當我們獲取到圖片或者視頻的縮略圖后,返回的是pixelMap,此時有開發(fā)者會有疑問如何將pixelMap轉換成jpeg等其他格式的圖片,其實使用image類中的packing方法就可以將pixelMap重新打包成新的格式(當前只支持jpeg,webp格式),再使用文件管理就可以將圖片存入到應用的沙箱路徑。本例即為大家介紹如何完成圖片格式轉換。
本例基于以下環(huán)境開發(fā),開發(fā)者也可以基于其他適配的版本進行開發(fā):
本例最終實現效果為:將工程資源文件中png格式的圖片轉換為jpg格式,并保存在設備中。由于本例不涉及UI講解,所以不在此提供UI效果。
本例中完成圖片格式轉換包含三個關鍵步驟,相關步驟及實現方案如下:
由于本例重點講解圖片格式的轉換,所以開發(fā)步驟會著重講解相關實現,不相關的內容不做介紹,全量代碼可參考完整代碼章節(jié)。
獲取要轉換圖片的PixelMap數據。
先通過上下文context獲取到資源管理器resourceManager,然后通過資源管理器獲取到圖片數據,然后獲取圖片的ArrayBuffer,最后通過ArrayBuffer創(chuàng)建imageSource,獲取到pixelMap,完成圖片解碼。
具體代碼如下:
import common from '@ohos.app.ability.common';
@Entry
@Component
struct Index {
...
context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext
...
async getPixelMap(){
// 獲取resourceManager資源管理
const resourceMgr = this.context.resourceManager
// 獲取rawfile文件夾下imagetransfer.PNG的ArrayBuffer
const fileData = await resourceMgr.getMediaContent($r('app.media.imagetransfer'))
const buffer = fileData.buffer
// 創(chuàng)建imageSource
const imageSource = image.createImageSource(buffer)
// 獲取PixelMap
const pixelMap = await imageSource.createPixelMap()
return pixelMap
}
...
}將圖片的PixelMap重新打包轉換為其他格式。
先通過createImagePacker構建ImagePacker實例,再通過該實例調用packing方法進行打包,打包時傳入獲取到的PixelMap數據及重新打包的圖片格式等相關配置信息。
具體代碼如下:
...
@State src:PixelMap = undefined
...
// 頁面加載前將獲取到的圖片PixelMap數據賦值給狀態(tài)變量src
async aboutToAppear() {
this.src = await this.getPixelMap()
}
...
// 創(chuàng)建ImagePacker實例
let imagePackerApi = image.createImagePacker();
let options = {
// 設置重新打包的圖片格式
format: 'image/jpeg',
quality: 98
};
// 打包時傳入圖片的PixelMap:src和圖片打包選項:option,異步獲取打包后的數據data
imagePackerApi.packing(this.src, options).then((data) => {
console.log('Succeeded in packing the image.');
}).catch(error => {
console.log('Failed to pack the image..');
....
})將重新打包好的圖片保存到應用目錄。
使用圖庫選擇器photoViewPicker保存文件,保存時可以在保存界面選擇保存路徑并設定文件名。此時保存的是空文件,然后再使用file將重新打包的圖片數據寫入保存的文件中,保存完成后我們便可以在保存路徑下找到轉換格式后的圖片文件了。
具體代碼如下:
...
// 打包時傳入圖片的pixelmap:src和圖片打包選項:option,異步獲取打包后的數據data
imagePackerApi.packing(this.src, options).then((data) => {
// 創(chuàng)建文件管理器保存選項實例
let photoSaveOptions = new picker.PhotoSaveOptions();
// 保存文件名(可選)
photoSaveOptions.newFileNames = ["imageTransfer.jpg"];
let photoViewPicker = new picker.PhotoViewPicker();
// 保存時傳入保存的文件名:photoSaveOptions
photoViewPicker.save(photoSaveOptions)
.then((photoSaveResult) => {
setTimeout(() => {
// 獲取到保存文件的URI,后續(xù)進行文件讀取等操作
this.uri = photoSaveResult[0];
fs.open(this.uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE).then((file) => {
// 將圖片打包數據data寫入保存的文件
fs.write(file.fd, data).then((number) => {
console.info("foo imagetest: write data to file succeed and size is:" + number);
}).catch((err) => {
console.info("foo imagetest: write data to file failed with error:" + err);
});
// 完成文件寫入后,關閉文件
fs.close(file, (err) => {
if (err) {
console.info("close file failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("close file success");
}
});
}).catch((err) => {
console.info("foo open file failed with error message: " + err.message + ", error code: " + err.code);
});
}, 200)
})
.catch((err) => {
console.error('PhotoViewPicker.save failed with err: ' + err);
})
})
...
本例完整代碼如下:
import image from '@ohos.multimedia.image';
import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import picker from '@ohos.file.picker';
@Entry
@Component
struct Index {
@State src:PixelMap = undefined
context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext
private uri = null
// 頁面加載前將獲取到的圖片PixelMap數據賦值給狀態(tài)變量src
async aboutToAppear() {
this.src = await this.getPixelMap()
}
async getPixelMap(){
// 獲取resourceManager資源管理
const resourceMgr = this.context.resourceManager
// 獲取rawfile文件夾下httpimage.PNG的ArrayBuffer
const fileData = await resourceMgr.getMediaContent($r('app.media.contact6'))
const buffer = fileData.buffer
// 創(chuàng)建imageSource
const imageSource = image.createImageSource(buffer)
// 創(chuàng)建PixelMap
const pixelMap = await imageSource.createPixelMap()
return pixelMap
console.log('pixelMap ' + JSON.stringify(this.src.getPixelBytesNumber()))
}
build() {
Row() {
Column() {
Button('轉換圖片格式:png->jpeg')
.onClick(() => {
// 創(chuàng)建ImagePacker實例
let imagePackerApi = image.createImagePacker();
// 設置重新打包的圖片格式,及圖片壓縮質量
let options = {
format: 'image/jpeg',
quality: 98
};
// 打包時傳入圖片的pixelmap:src和圖片打包選項:option,異步獲取打包后的數據data
imagePackerApi.packing(this.src, options).then((data) => {
// 創(chuàng)建文件管理器保存選項實例
let photoSaveOptions = new picker.PhotoSaveOptions();
// 保存文件名(可選)
photoSaveOptions.newFileNames = ["imageTransfer.jpg"];
let photoViewPicker = new picker.PhotoViewPicker();
// 保存時傳入保存的文件名:photoSaveOptions
photoViewPicker.save(photoSaveOptions)
.then((photoSaveResult) => {
console.log('foo start')
setTimeout(() => {
// 獲取到圖片的URI后進行文件讀取等操作
this.uri = photoSaveResult[0];
fs.open(this.uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE).then((file) => {
// 將圖片打包數據data寫入保存的文件
fs.write(file.fd, data).then((number) => {
console.info("foo imagetest: write data to file succeed and size is:" + number);
}).catch((err) => {
console.info("foo imagetest: write data to file failed with error:" + err);
});
// 完成文件寫入后,關閉文件
fs.close(file, (err) => {
if (err) {
console.info("close file failed with error message: " + err.message + ", error code: " + err.code);
} else {
console.info("close file success");
}
});
}).catch((err) => {
console.info("foo open file failed with error message: " + err.message + ", error code: " + err.code);
});
}, 200)
})
.catch((err) => {
console.error('PhotoViewPicker.save failed with err: ' + err);
})
})
})
}
.width('100%')
}
.height('100%')
}
}想了解更多關于開源的內容,請訪問:
開源基礎軟件社區(qū)
https://ost.

我們在微信上24小時期待你的聲音
解答本文疑問/技術咨詢/運營咨詢/技術建議/互聯網交流