GWT Canvas - Save image and open it

2019-08-22 02:32发布

问题:

I save an image in a String, then when I open it it's always 300x150

Why is the image truncated?

Where does 300x150 come from?

The code is what you see. Just 2 buttons.

The first one saves the image in "png", and the other reads the image from "png"

                    Button save = new Button("copy");
                    save.addClickHandler(new ClickHandler() {
                        @Override
                        public void onClick(ClickEvent event) {
                            ImageElement imageElement = ImageElement.as(image.getElement());

                            Canvas canvasTmp = Canvas.createIfSupported();
                            Context2d context = canvasTmp.getContext2d();
                            context.drawImage(imageElement, 0.0, 0.0, imageElement.getWidth(), imageElement.getHeight());
                            png = canvasTmp.toDataUrl("image/png");
                        }
                    });

                    Button open = new Button("open");
                    open.addClickHandler(new ClickHandler() {

                        @Override
                        public void onClick(ClickEvent event) {

                            final Image image = new Image(png);
                            vp.add(image);
                            image.addLoadHandler(new LoadHandler() {

                                @Override
                                public void onLoad(LoadEvent event) 
                                {
                                    Window.alert("ok");
                                }
                            });

                            image.addErrorHandler(new ErrorHandler() {

                                @Override
                                public void onError(ErrorEvent event) {
                                    Window.alert("error");
                                }
                            } );

                        }
                    });

回答1:

The canvas has a default width of 300 pixels and a default height of 150 pixels. After creating the canvas and before drawing the image, consider doing this:

int width = imageElement.getWidth()
int height = imageElement.getHeight()
canvasTmp.setWidth(width + "px");
canvasTmp.setHeight(height + "px");
canvasTmp.setCoordinateSpaceWidth(width);
canvasTmp.setCoordinateSpaceHeight(height);