@@ -489,24 +489,35 @@ void cmd_image_save(var_s *self, var_s *) {
489489 !encode_png_file (var->v .p .ptr , image->_image , w, h)) {
490490 saved = true ;
491491 } else if (!prog_error) {
492- u_int32_t offsetLeft = map_get_int (self, IMG_OFFSET_LEFT, -1 );
493- u_int32_t offsetTop = map_get_int (self, IMG_OFFSET_TOP, -1 );
494- u_int32_t wClip = map_get_int (self, IMG_WIDTH, -1 );
495- u_int32_t hClip = map_get_int (self, IMG_HEIGHT, -1 );
496- v_tomatrix (var, hClip, wClip);
497- // x0 x1 x2 (w=3,h=2)
498- // y0 rgba rgba rgba ypos=0
499- // y1 rgba rgba rgba ypos=12
500- //
501- for (unsigned y = offsetTop; y < offsetTop + hClip; y++) {
502- unsigned yoffs = (y * w * 4 );
503- for (unsigned x = offsetLeft; x < offsetLeft + wClip; x++) {
504- uint8_t a, r, g, b;
505- GET_IMAGE_ARGB (image->_image , yoffs + (x * 4 ), a, r, g, b);
506- pixel_t px = v_get_argb_px (a, r, g, b);
507- unsigned pos = (y - offsetTop ) * wClip + (x - offsetLeft);
508- v_setint (v_elem (var, pos), px);
492+ uint32_t offsetLeft = map_get_int (self, IMG_OFFSET_LEFT, 0 );
493+ uint32_t offsetTop = map_get_int (self, IMG_OFFSET_TOP, 0 );
494+ uint32_t wClip = map_get_int (self, IMG_WIDTH, w);
495+ uint32_t hClip = map_get_int (self, IMG_HEIGHT, h);
496+
497+ if (offsetTop < h && offsetLeft < w) {
498+ if (offsetTop + hClip > h) {
499+ hClip = h - offsetTop;
509500 }
501+ if (offsetLeft + wClip > w) {
502+ wClip = w - offsetLeft;
503+ }
504+ v_tomatrix (var, hClip, wClip);
505+ // x0 x1 x2 (w=3,h=2)
506+ // y0 rgba rgba rgba ypos=0
507+ // y1 rgba rgba rgba ypos=12
508+ //
509+ for (unsigned y = offsetTop; y < offsetTop + hClip; y++) {
510+ unsigned yoffs = (y * w * 4 );
511+ for (unsigned x = offsetLeft; x < offsetLeft + wClip; x++) {
512+ uint8_t a, r, g, b;
513+ GET_IMAGE_ARGB (image->_image , yoffs + (x * 4 ), a, r, g, b);
514+ pixel_t px = v_get_argb_px (a, r, g, b);
515+ unsigned pos = (y - offsetTop ) * wClip + (x - offsetLeft);
516+ v_setint (v_elem (var, pos), px);
517+ }
518+ }
519+ } else {
520+ v_tomatrix (var, hClip, wClip);
510521 }
511522 saved = true ;
512523 }
@@ -531,6 +542,12 @@ void cmd_image_clip(var_s *self, var_s *) {
531542 ImageBuffer *image = get_image ((unsigned )bid);
532543 var_int_t left, top, width, heigth;
533544 if (image != nullptr && par_massget (" iiii" , &left, &top, &width, &heigth)) {
545+ if (left < 0 ) {
546+ left = 0 ;
547+ }
548+ if (top < 0 ) {
549+ top = 0 ;
550+ }
534551 map_set_int (self, IMG_OFFSET_LEFT, left);
535552 map_set_int (self, IMG_OFFSET_TOP, top);
536553 map_set_int (self, IMG_WIDTH, width);
0 commit comments