【问题标题】:Is it possible to reduce the image size by decodeWidth and decodeHeight properties是否可以通过 decodeWidth 和 decodeHeight 属性减小图像大小
【发布时间】:2019-06-05 15:03:54
【问题描述】:

我正在尝试在线保存从相机拍摄的图像。但是图像大小超过了 MB。

我遇到了 decodeWidth 和 decodeHeight 属性,但不知道它是如何工作的。是否可以减小从这些属性中获取的图像的大小。

<StackLayout>
    <Image src="" decodeWidth="400" decodeHeight="400" loadMode="async" />
    <Label text="With loadMode set to async the UI won't be blocked" 
     textWrap="true" />
</StackLayout>

在上传之前,我需要将图像的大小减小到 50 像素或更小。如何做到这一点。

我尝试了类似的方法,但图像未保存。

 let ImageAsset = require('tns-core-modules/image-asset').ImageAsset;

  const asset = new ImageAsset("~/images/nature.jpg");
  asset.options = {
    width: 100,
    height: 100,
    keepAspectRatio: true
  };
  console.log(asset);

  const imageSourceModule = require("tns-core-modules/image-source");
  const fileSystemModule = require("tns-core-modules/file-system");
  const img = imageSourceModule.fromFile(asset._android);
  const folderRoot = fileSystemModule.knownFolders.documents();
  folderRoot._path = "/storage/emulated/0/";
  const folder = folderRoot.getFolder("AAAA/");
  const pathDest = fileSystemModule.path.join(folder._path, `sample.jpg`);

  const exists = fileSystemModule.File.exists(pathDest);

  if (exists == true) {
    const saved = img.saveToFile(pathDest, "jpg");
    if (saved) {
      console.log("Image saved successfully!");
    }
  } else {
    console.log("Image not saved successfully!");
  }
console 

JS: {
JS:   "_observers": {},
JS:   "_options": {
JS:     "width": 100,
JS:     "height": 100,
JS:     "keepAspectRatio": true
JS:   },
JS:   "_android": "/data/data/org.nativescript.cameraplus/files/app/images/nature.jpg"
JS: }
JS: Image not saved successfully!

【问题讨论】:

    标签: nativescript


    【解决方案1】:

    decodeWidth / decodeHeight 有助于在Image 组件上加载较低分辨率的图像。

    要获得调整大小的图像,您可以执行以下操作

    import { ImageAsset } from 'tns-core-modules/image-asset';
    
    const asset = new ImageAsset(path);
    asset.options = {
      width: 100,
      height: 100,
      keepAspectRatio: true
    };
    

    您可以在图片资源上调用getImageAsync() 以获取调整大小的原生图片数据,或者直接将其保存到文件并上传。

    更新:

    要保存图片,使用图片源模块如下

    imageSourceModule.fromAsset(asset)
     .then(img => img.saveToFile(pathDest, "jpg"));
    

    【讨论】:

    • 我尝试了上述答案,但没有保存图像。我已经编辑了我尝试过的问题本身。如有错误请指正。
    • 这工作正常,是他们提高图像清晰度并将尺寸减小到 50 像素的任何方法。现在 W 100 和 H 100 的 1.21MB 图像减少到 22.95KB,我能以像素为单位给出宽度和高度吗,它会影响不同的屏幕设备。
    • 你能澄清一下这里的 100 是什么吗?无论是在 Pixel 还是其他东西中。缩小后的图像大小在所有设备上都相同..!
    • 是的,这些都是像素。
    • 我要求太多了,这是最后一个。 w 100Px 和 h 100Px 如何转换为 KB。如果你不介意,请。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-20
    相关资源
    最近更新 更多