react版

    1. export default class Home extends React.Component {
    2. constructor(props) {
    3. super(props);
    4. this.state = {
    5. url: ''
    6. }
    7. }
    8. changeFile (event) {
    9. var _this = this;
    10. // 选择的文件对象(file里只包含图片的体积,不包含图片的尺寸)
    11. var file = event.target.files[0];
    12. console.log(file)
    13. // 选择的文件是图片
    14. if(file.type.indexOf("image") === 0) {
    15. // 压缩图片需要的一些元素和对象
    16. var reader = new FileReader(),
    17. //创建一个img对象
    18. img = new Image();
    19. reader.readAsDataURL(file);
    20. // 文件base64化,以便获知图片原始尺寸
    21. reader.onload = function(e) {
    22. img.src = e.target.result;
    23. };
    24. // base64地址图片加载完毕后执行
    25. img.onload = function () {
    26. // 缩放图片需要的canvas(也可以在DOM中直接定义canvas标签,这样就能把压缩完的图片不转base64也能直接显示出来)
    27. var canvas = document.createElement('canvas');
    28. var context = canvas.getContext('2d');
    29. // 图片原始尺寸
    30. var originWidth = this.width;
    31. var originHeight = this.height;
    32. // 最大尺寸限制,可通过设置宽高来实现图片压缩程度
    33. var maxWidth = 300,
    34. maxHeight = 300;
    35. // 目标尺寸
    36. var targetWidth = originWidth,
    37. targetHeight = originHeight;
    38. // 图片尺寸超过300x300的限制
    39. if(originWidth > maxWidth || originHeight > maxHeight) {
    40. if(originWidth / originHeight > maxWidth / maxHeight) {
    41. // 更宽,按照宽度限定尺寸
    42. targetWidth = maxWidth;
    43. targetHeight = Math.round(maxWidth * (originHeight / originWidth));
    44. } else {
    45. targetHeight = maxHeight;
    46. targetWidth = Math.round(maxHeight * (originWidth / originHeight));
    47. }
    48. }
    49. // canvas对图片进行缩放
    50. canvas.width = targetWidth;
    51. canvas.height = targetHeight;
    52. // 清除画布
    53. context.clearRect(0, 0, targetWidth, targetHeight);
    54. // 图片压缩
    55. context.drawImage(img, 0, 0, targetWidth, targetHeight);
    56. /*第一个参数是创建的img对象;第二三个参数是左上角坐标,后面两个是画布区域宽高*/
    57. //压缩后的图片转base64 url
    58. /*canvas.toDataURL(mimeType, qualityArgument),mimeType 默认值是'image/png';
    59. * qualityArgument表示导出的图片质量,只有导出为jpeg和webp格式的时候此参数才有效,默认值是0.92*/
    60. var newUrl = canvas.toDataURL('image/jpeg', 0.92);//base64 格式
    61. _this.setState({
    62. url: newUrl
    63. })
    64. //也可以把压缩后的图片转blob格式用于上传
    65. // canvas.toBlob((blob)=>{
    66. // console.log(blob)
    67. // //把blob作为参数传给后端
    68. // }, 'image/jpeg', 0.92)
    69. };
    70. } else {
    71. alert('请上传图片格式');
    72. }
    73. }
    74. render() {
    75. let { url } = this.state;
    76. return (
    77. <div>
    78. <input id="file" type="file" onChange={this.changeFile.bind(this)}/>
    79. <img id="preview" src={ url } alt="" />
    80. </div>
    81. )
    82. }
    83. }

    小程序:

    1. <button bindtap="chooseImg">选择图片</button>
    2. <canvas canvas-id="firstCanvas" style="width:{{ imgWidth }}px; height:{{ imgHeight }}px;"></canvas>
    1. Page({
    2. data: {
    3. imgWidth: 0,
    4. imgHeight: 0
    5. },
    6. chooseImg () {
    7. let _this = this;
    8. // 从本地相册选择图片或使用相机拍照
    9. wx.chooseImage({
    10. count: 1, // 最多可以选择的图片张数
    11. success (res) {
    12. const ctx = wx.createCanvasContext('firstCanvas');
    13. let path = res.tempFilePaths[0];
    14. wx.getImageInfo({
    15. src: path,
    16. success (res) {
    17. console.log(res)
    18. // 图片原始尺寸
    19. let originWidth = res.width;
    20. let originHeight = res.height;
    21. // 最大尺寸限制,可通过设置宽高来实现图片压缩程度
    22. let maxWidth = 200,
    23. maxHeight = 150;
    24. // 目标尺寸
    25. let targetWidth = originWidth,
    26. targetHeight = originHeight;
    27. // 图片尺寸超过200x150的限制
    28. if(originWidth > maxWidth || originHeight > maxHeight) {
    29. if(originWidth / originHeight > maxWidth / maxHeight) {
    30. // 更宽,按照宽度限定尺寸
    31. targetWidth = maxWidth;
    32. targetHeight = Math.round(maxWidth * (originHeight / originWidth));
    33. } else {
    34. targetHeight = maxHeight;
    35. targetWidth = Math.round(maxHeight * (originWidth / originHeight));
    36. }
    37. }
    38. // canvas对图片进行缩放
    39. _this.setData({
    40. imgWidth: targetWidth,
    41. imgHeight: targetHeight
    42. })
    43. // 压缩图片(绘制图像到画布)
    44. ctx.drawImage(path,0,0,targetWidth,targetHeight);
    45. ctx.draw(false, ()=>{
    46. // canvas导出为图片路径
    47. wx.canvasToTempFilePath({
    48. canvasId: 'firstCanvas',
    49. fileType: 'jpg', //支持jpg或png
    50. quality: 0.92, //图片质量
    51. success(res) {
    52. let path = res.tempFilePath;
    53. // 保存图片到系统相册
    54. wx.saveImageToPhotosAlbum({
    55. filePath: path,
    56. success () {
    57. console.log('保存到本地相册成功!')
    58. },
    59. fail () {
    60. console.log('保存到本地相册失败!')
    61. }
    62. })
    63. // 上传压缩过的图片
    64. http.upload_file('/pic/uploadPic', path, 'file', (res)=>{})
    65. },
    66. fail(err) {
    67. console.log(err);
    68. }
    69. })
    70. });
    71. }
    72. })
    73. }
    74. })
    75. }
    76. })