void update() { m_pImage->clear(0xff000000); // a=ff, r=00, g=00, b=00 HelloModel* pModel = m_pController->model(); m_pImage->text(g_szMessage, pModel->x(), pModel->y(), TEXT_SIZE, 0xffffff30); // a=ff, r=ff, g=ff, b=30 m_pCanvas->setImage(m_pImage); }
void silhouetteCount(string nameImageFile){ int silhouetteCounter=0; GImage* imageFile = new GImage(nameImageFile); GBufferedImage* imgageInBuffer = new GBufferedImage(0,0,imageFile->getWidth(), imageFile->getHeight()); imgageInBuffer->load(nameImageFile); int imgHaight = imgageInBuffer->getHeight(); int imgWidth = imgageInBuffer->getWidth(); GWindow gw(imgWidth, imgHaight); gw.add(imageFile); myGrid imageBinaring(imgHaight, imgWidth); binaringImageToGrid(imgageInBuffer, imageBinaring); bool silhouetteIsValid = false; for(int x = 0; x < imgHaight; x++){ for (int y = 0; y < imgWidth; y++){ if (imageBinaring.get_color(x,y) == true && imageBinaring.get_visited(x,y) == false) { selectFindeArea(x,y, imageBinaring, silhouetteIsValid); if (silhouetteIsValid) silhouetteCounter++; } } } cout<<"in File: "<<nameImageFile<<"; found "<< silhouetteCounter<<" silhouettes."<<endl; cout<<endl; delete imgageInBuffer; delete imageFile; }
HelloDialog(HelloController* pController, int w, int h) : GWidgetDialog(w, h, 0xff90d0f0) // a=ff, r=90, g=d0, b=f0 { m_pController = pController; m_pImage = new GImage(); m_pImage->setSize(800, 600); m_pCanvas = new GWidgetCanvas(this, 10, 30, m_pImage->width(), m_pImage->height(), m_pImage); m_pQuitButton = new GWidgetTextButton(this, 850, 300, 80, 24, "Quit"); }
void DrawCar() { double angle = atan(3 * (2 * m_carPos - 3 * m_carPos * m_carPos)); m_pRotatedCar->rotate(m_pCar, 35, 41, angle); double y = m_carPos * m_carPos - m_carPos * m_carPos * m_carPos; int i = (int)((m_carPos + 0.4) * m_pImage->width() / 1.4); int j = (int)(m_pImage->height() - y * 3 * m_pImage->height() - 50); GRect r(0, 0, 70, 60); m_pImage->blitAlpha(i - 35, j - 40, m_pRotatedCar, &r); }
// static void GSubImageFinder2::test() { // Make some random image GImage foo; foo.setSize(256, 256); foo.clear(0xff000000); foo.boxFill(13, 8, 12, 17, 0xff808030); foo.boxFill(8, 13, 10, 9, 0xff407040); foo.boxFill(20, 20, 220, 220, 0xffffffee); // Make the finder GSubImageFinder2 finder(&foo); // Make a sub-image GRect r2(0, 0, 256, 256); GRect r; r.x = 13; r.y = 17; r.w = 32; r.h = 32; GImage bar; bar.setSize(32, 32); bar.blit(0, 0, &foo, &r); // Find the sub-image r.x = 0; r.y = 0; int x, y; finder.findSubImage(&x, &y, &bar, &r); if(x != 13 || y != 17) throw "wrong answer"; }
PopupView(GWidgetDialog* pDialog) : ViewBase() { m_nLeft = 0; m_nTop = 0; m_pBackgroundImage = new GImage(); captureScreen(m_pBackgroundImage); m_pBackgroundImage->contrastAndBrightness(.5, -64); m_pDialog = pDialog; m_x = (m_pBackgroundImage->width() - m_pDialog->rect()->w) / 2; m_y = (m_pBackgroundImage->height() - m_pDialog->rect()->h) / 2; }
void Image4uint8::copyGImage(const GImage& im) { switch (im.channels()) { case 1: copyArray(im.pixel1(), im.width(), im.height()); break; case 3: copyArray(im.pixel3(), im.width(), im.height()); break; case 4: copyArray(im.pixel4(), im.width(), im.height()); break; } }
void test_image() { GImage *im = new GImage("avatar.gif"); // in images subdirectory GImage *webIm = new GImage("http://tikiloungetalk.com/wp-content/uploads/2010/11/speedracer-old.jpg"); #ifdef _WIN32 GImage *absPathIm = new GImage("C:/Qt/Qt5.3.2/Tools/QtCreator/share/qtcreator/qmlicons/Qt/16x16/CountBubble.png"); #else GImage *absPathIm = new GImage("/usr/share/doc/cups/images/smiley.jpg"); #endif gw->add(im, 10, 10); int x = 10 + im->getWidth(); gw->add(webIm, x, 10); x += webIm->getWidth(); gw->add(absPathIm, x, 10); }
Image4uint8::Ref Image4uint8::fromGImage(const GImage& im, WrapMode wrap) { switch (im.channels()) { case 1: return fromArray(im.pixel1(), im.width(), im.height(), wrap); case 3: return fromArray(im.pixel3(), im.width(), im.height(), wrap); case 4: return fromArray(im.pixel4(), im.width(), im.height(), wrap); default: debugAssertM(false, "Input GImage must have 1, 3, or 4 channels."); return NULL; } }
// static void GPlotWindow::stringLabel(GImage* pImage, const char* szText, int x, int y, float size, unsigned int color, double angle) { // Draw the label such that it ends at the center of the temp image int width = GImage::measureTextWidth(szText, size); int nSize = (int)(std::max((float)width, size * 12) * 2.3); GImage tmp; tmp.setSize(nSize, nSize); tmp.clear(0x0); tmp.text(szText, nSize / 2 - width, (int)((nSize - size * 12) / 2), size, color, 1000, 1000); // Rotate the label around the center GImage tmp2; tmp2.rotate(&tmp, nSize / 2, nSize / 2, angle); // Blit such that the label ends at the specified point GRect r(0, 0, nSize, nSize); pImage->blitAlpha(x - nSize / 2, y - nSize / 2, &tmp2, &r); }
void ViewNewAccount::MakeCaptcha(const char* szID, ostream& response) { char szText[32]; GetCaptchaText(szText, szID); std::ostringstream& r = reinterpret_cast<std::ostringstream&>(response); r.str(""); r.clear(); // Make the filename char szTemp[512]; GFile::tempFilename(szTemp); // Make the captcha GImage image; image.captcha(szText, m_pServer->prng()); image.savePng(szTemp); m_pServer->sendFile("image/png", szTemp, response); DeleteFile(szTemp); }
void G2DRegionGraph::makeWatershedRegions(const GImage* pImage) { GImage gradMag; gradMag.gradientMagnitudeImage(pImage); GImage* pMask = regionMask(); int x, y, u, v, du, dv; size_t region, other; for(y = 0; y < (int)pImage->height(); y++) { for(x = 0; x < (int)pImage->width(); x++) { u = x; v = y; do { region = pMask->pixel(u, v); if(region != 0xffffffff) break; PickTobogganDirection(&gradMag, u, v, &du, &dv); u += du; v += dv; } while(du != 0 || dv != 0); if(region == 0xffffffff) { region = addRegion(); setMaskPixel(u, v, pImage->pixel(u, v), region); } u = x; v = y; do { if(pMask->pixel(u, v) != 0xffffffff) break; setMaskPixel(u, v, pImage->pixel(u, v), region); PickTobogganDirection(&gradMag, u, v, &du, &dv); u += du; v += dv; } while(du != 0 || dv != 0); if(x > 0) { other = pMask->pixel(x - 1, y); if(other != region) makeNeighbors(region, other); } if(y > 0) { other = pMask->pixel(x, y - 1); if(other != region) makeNeighbors(region, other); } } } }
bool MarbleGraphics::makeMove(const Move move){ GImage * movingMarble = marbles[move.startRow][move.startCol]; int jumpedRow = move.startRow+(move.endRow-move.startRow)/2; int jumpedCol = move.startCol+(move.endCol-move.startCol)/2; GImage * jumpedMarble = marbles[jumpedRow][jumpedCol]; if (movingMarble == NULL || jumpedMarble == NULL){ return false; } //Move empty spot from end to start of move GOval* endSpot = spaces[move.endRow][move.endCol]; double tempX = endSpot->getX(); double tempY = endSpot->getY(); endSpot->setLocation(movingMarble->getX(), movingMarble->getY()); spaces[move.startRow][move.startCol] = endSpot; spaces[move.endRow][move.endCol] = NULL; spaceCoords[endSpot] = Coord(move.startRow, move.startCol); //Move image at start location to image at end location movingMarble->setLocation(tempX, tempY); marbles[move.endRow][move.endCol] = movingMarble; marbles[move.startRow][move.startCol] = NULL; marbleCoords[movingMarble] = Coord(move.endRow, move.endCol); //Delete marble for jumped space and create empty space there instead marbles[jumpedRow][jumpedCol] = NULL; marbleCoords.remove(jumpedMarble); remove(jumpedMarble); delete jumpedMarble; GOval* jumpedSpace = new GOval(kMarbleDimension, kMarbleDimension); spaces[jumpedRow][jumpedCol] = jumpedSpace; spaceCoords[jumpedSpace] = Coord(jumpedRow, jumpedCol); add(jumpedSpace, jumpedCol*(kMarbleDimension+kMarbleSpacingWidth)+kMarbleSpacingWidth, jumpedRow*(kMarbleDimension+kMarbleSpacingWidth)+kMarbleSpacingWidth); return true; }
CarOnHillModel(GRand* prng, GImage* pImage, GWidgetTextLabel* pWins) { m_pWins = pWins; m_wins = 0; m_pImage = pImage; m_carPos = 0; m_velocity = 0; m_prng = prng; // Load the car image and add some border so we can rotate it GImage tmp; tmp.loadPng("minicar.png"); m_pCar = new GImage(); m_pCar->setSize(70, 60); GRect r(0, 0, 60, 36); m_pCar->blit(5, 5, &tmp, &r); m_pRotatedCar = new GImage(); // Make the agent GMixedRelation* pRelAgent = new GMixedRelation(); sp_relation relAgent; relAgent = pRelAgent; pRelAgent->addAttr(0); // position pRelAgent->addAttr(0); // velocity pRelAgent->addAttr(2); // action {forward, reverse} double initialState[2]; initialState[0] = m_carPos; initialState[1] = m_velocity; double goalState[2]; goalState[0] = 2; goalState[1] = 0; m_pActionIterator = new GDiscreteActionIterator(2); m_pAgents[0] = new CarQAgent(relAgent, initialState, m_prng, m_pActionIterator); ((GQLearner*)m_pAgents[0])->setLearningRate(.9); ((GQLearner*)m_pAgents[0])->setDiscountFactor(0.999); }
CarOnHillDialog(CarOnHillController* pController, int w, int h) : GWidgetDialog(w, h, 0xff90d0f0) { m_pController = pController; m_pBullets = new GWidgetBulletGroup(this, 820, 102, 14, 14, 2, 30, true); new GWidgetTextLabel(this, 840, 100, 100, 24, "Mouse", 0xff306000); new GWidgetTextLabel(this, 840, 130, 100, 24, "Q-Learner", 0xff306000); m_pBullets->setSelection(1); m_pWins = new GWidgetTextLabel(this, 820, 300, 100, 24, "Wins: 0", 0xff306000, 0xff90d0f0); m_pUpdateDisplay = new GWidgetCheckBox(this, 820, 402, 18, 18); m_pUpdateDisplay->setChecked(true); new GWidgetTextLabel(this, 840, 400, 100, 24, "Slow", 0xff306000); m_pImage = new GImage(); m_pImage->setSize(800, 600); m_pCanvas = new GWidgetCanvas(this, 10, 30, m_pImage->width(), m_pImage->height(), m_pImage); m_prng = new GRand(0); m_pModel = new CarOnHillModel(m_prng, m_pImage, m_pWins); m_bPrevUpdate = true; }
void Redraw(bool forw) { m_pImage->clear(0xff80c0e0); // Draw the hill { int i, j; double x, y; for(i = 0; i < (int)m_pImage->width(); i++) { x = (double)i * 1.4 / m_pImage->width() - 0.4; y = x * x - x * x * x; j = (int)(m_pImage->height() - y * 3 * m_pImage->height() - 50); m_pImage->lineNoChecks(i, j, i, m_pImage->height() - 1, 0xff40a060); } } // Draw the car DrawCar(); // Draw the acceleration arrow m_pImage->arrow(240, 20, 240 + (forw ? 15 : -15), 20, 0xff000000, 10); }
void SDLWindow::setIcon(const GImage& image) { alwaysAssertM((image.channels == 3) || (image.channels == 4), "Icon image must have at least 3 channels."); #ifdef G3D_WIN32 alwaysAssertM((image.width == 32) && (image.height == 32), "Icons must be 32x32 on windows."); #endif uint32 amask = 0xFF000000; uint32 bmask = 0x00FF0000; uint32 gmask = 0x0000FF00; uint32 rmask = 0x000000FF; if (image.channels == 3) { // Take away the 4th channel. amask = 0x00000000; } int pixelBitLen = image.channels * 8; int scanLineByteLen = image.channels * image.width; SDL_Surface* surface = SDL_CreateRGBSurfaceFrom((void*)image.byte(), image.width, image.height, pixelBitLen, scanLineByteLen, rmask, gmask, bmask, amask); alwaysAssertM((surface != NULL), "Icon data failed to load into SDL."); // Let SDL create mask from image data directly SDL_WM_SetIcon(surface, NULL); SDL_FreeSurface(surface); }
SDLWindow::SDLWindow(const GWindow::Settings& settings) { #if defined(G3D_OSX) NSApplicationWrapper wrapper; // Hack to get our window/process to the front... ProcessSerialNumber psn = { 0, kCurrentProcess}; TransformProcessType (&psn, kProcessTransformToForegroundApplication); SetFrontProcess (&psn); _pool = new NSAutoreleasePoolWrapper(); #endif if (SDL_Init(SDL_INIT_NOPARACHUTE | SDL_INIT_VIDEO | SDL_INIT_JOYSTICK) < 0 ) { fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError()); debugPrintf("Unable to initialize SDL: %s\n", SDL_GetError()); Log::common()->printf("Unable to initialize SDL: %s\n", SDL_GetError()); exit(1); } // Set default icon if available if (settings.defaultIconFilename != "nodefault") { try { GImage defaultIcon; defaultIcon.load(settings.defaultIconFilename); setIcon(defaultIcon); } catch (const GImage::Error& e) { // Throw away default icon fprintf(stderr, "GWindow's default icon failed to load: %s (%s)", e.filename.c_str(), e.reason.c_str()); debugPrintf("GWindow's default icon failed to load: %s (%s)", e.filename.c_str(), e.reason.c_str()); Log::common()->printf("GWindow's default icon failed to load: %s (%s)", e.filename.c_str(), e.reason.c_str()); } } if (! settings.fullScreen) { // This doesn't really work very well due to SDL bugs so we fix up // the position after the window is created. if (settings.center) { System::setEnv("SDL_VIDEO_CENTERED", ""); } else { System::setEnv("SDL_VIDEO_WINDOW_POS", format("%d,%d", settings.x, settings.y)); } } _mouseVisible = true; _inputCapture = false; // Request various OpenGL parameters SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, settings.depthBits); SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1); SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, settings.stencilBits); SDL_GL_SetAttribute(SDL_GL_RED_SIZE, settings.rgbBits); SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, settings.rgbBits); SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, settings.rgbBits); SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, settings.alphaBits); SDL_GL_SetAttribute(SDL_GL_STEREO, settings.stereo); #if SDL_FSAA if (settings.fsaaSamples > 1) { SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1); SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, settings.fsaaSamples); } #endif // Create a width x height OpenGL screen int flags = SDL_HWSURFACE | SDL_OPENGL | (settings.fullScreen ? SDL_FULLSCREEN : 0) | (settings.resizable ? SDL_RESIZABLE : 0) | (settings.framed ? 0 : SDL_NOFRAME); if (SDL_SetVideoMode(settings.width, settings.height, 0, flags) == NULL) { debugAssert(false); Log::common()->printf("Unable to create OpenGL screen: %s\n", SDL_GetError()); error("Critical Error", format("Unable to create OpenGL screen: %s\n", SDL_GetError()).c_str(), true); SDL_Quit(); exit(2); } // See what video mode we really got _settings = settings; int depthBits, stencilBits, redBits, greenBits, blueBits, alphaBits; glGetIntegerv(GL_DEPTH_BITS, &depthBits); glGetIntegerv(GL_STENCIL_BITS, &stencilBits); glGetIntegerv(GL_RED_BITS, &redBits); glGetIntegerv(GL_GREEN_BITS, &greenBits); glGetIntegerv(GL_BLUE_BITS, &blueBits); glGetIntegerv(GL_ALPHA_BITS, &alphaBits); int actualFSAABuffers = 0, actualFSAASamples = 0; #if SDL_FSAA SDL_GL_GetAttribute(SDL_GL_MULTISAMPLEBUFFERS, &actualFSAABuffers); SDL_GL_GetAttribute(SDL_GL_MULTISAMPLESAMPLES, &actualFSAASamples); #else (void)actualFSAABuffers; (void)actualFSAASamples; #endif _settings.rgbBits = iMin(iMin(redBits, greenBits), blueBits); _settings.alphaBits = alphaBits; _settings.stencilBits = stencilBits; _settings.depthBits = depthBits; _settings.fsaaSamples = actualFSAASamples; SDL_version ver; SDL_VERSION(&ver); _version = format("%d,%0d.%0d", ver.major, ver.minor, ver.patch); SDL_EnableUNICODE(1); setCaption("G3D"); SDL_SysWMinfo info; SDL_VERSION(&info.version); SDL_GetWMInfo(&info); _glContext = glGetCurrentContext(); #if defined(G3D_WIN32) // Extract SDL HDC/HWND on Win32 _Win32HWND = info.window; _Win32HDC = wglGetCurrentDC(); #elif defined(G3D_LINUX) // Extract SDL's internal Display pointer on Linux _X11Display = info.info.x11.display; _X11Window = info.info.x11.window; _X11WMWindow = info.info.x11.wmwindow; if (glXGetCurrentDisplay != NULL) { G3D::_internal::x11Display = glXGetCurrentDisplay(); } else { G3D::_internal::x11Display = info.info.x11.display; } if (glXGetCurrentDrawable != NULL) { // A Drawable appears to be either a Window or a Pixmap G3D::_internal::x11Window = glXGetCurrentDrawable(); } else { G3D::_internal::x11Window = info.info.x11.window; } #endif // Adjust window position #ifdef G3D_WIN32 if (! settings.fullScreen) { int W = screenWidth(); int H = screenHeight(); int x = iClamp(settings.x, 0, W); int y = iClamp(settings.y, 0, H); if (settings.center) { x = (W - settings.width) / 2; y = (H - settings.height) / 2; } SetWindowPos(_Win32HWND, NULL, x, y, 0, 0, SWP_NOZORDER | SWP_NOSIZE); } #endif #ifdef G3D_LINUX if (! settings.fullScreen) { int W = screenWidth(_X11Display); int H = screenHeight(_X11Display); int x = iClamp(settings.x, 0, W); int y = iClamp(settings.y, 0, H); if (settings.center) { x = (W - settings.width) / 2; y = (H - settings.height) / 2; } XMoveWindow(_X11Display, _X11WMWindow, x, y); } #endif // Check for joysticks int j = SDL_NumJoysticks(); if ((j < 0) || (j > 10)) { // If there is no joystick adapter on Win32, // SDL returns ridiculous numbers. j = 0; } if (j > 0) { SDL_JoystickEventState(SDL_ENABLE); // Turn on the joysticks joy.resize(j); for (int i = 0; i < j; ++i) { joy[i] = SDL_JoystickOpen(i); debugAssert(joy[i]); } } GLCaps::init(); // Register this window as the current window makeCurrent(); # if defined(G3D_LINUX) // If G3D is using the default assertion hooks, replace them with our own that use // SDL functions to release the mouse, since we've been unable to implement // a non-SDL way of releasing the mouse using the X11 handle directly. if (assertionHook() == _internal::_handleDebugAssert_) { setFailureHook(SDL_handleDebugAssert_); } if (failureHook() == _internal::_handleErrorCheck_) { setFailureHook(SDL_handleErrorCheck_); } # endif }
virtual void draw(SDL_Surface *pScreen) { GImage* pDialogImage = m_pDialog->image(); m_pBackgroundImage->blit(m_x, m_y, pDialogImage, m_pDialog->rect()); blitImage(pScreen, m_nLeft, m_nTop, m_pBackgroundImage); }
void G2DRegionGraph::makeCoarserRegions(G2DRegionGraph* pFineRegions) { // Find every region's closest neighbor GImage* pFineRegionMask = pFineRegions->regionMask(); GImage* pCoarseRegionMask = regionMask(); GAssert(pCoarseRegionMask->width() == pFineRegionMask->width() && pCoarseRegionMask->height() == pFineRegionMask->height()); // size mismatch int* pBestNeighborMap = new int[pFineRegions->regionCount()]; ArrayHolder<int> hBestNeighborMap(pBestNeighborMap); for(size_t i = 0; i < pFineRegions->regionCount(); i++) { struct GRegion* pRegion = pFineRegions->m_regions[i]; struct GRegionEdge* pEdge; double d; double dBestDiff = 1e200; int nBestNeighbor = -1; for(pEdge = pRegion->m_pNeighbors; pEdge; pEdge = pEdge->GetNext(i)) { size_t j = pEdge->GetOther(i); struct GRegion* pOtherRegion = pFineRegions->m_regions[j]; d = MeasureRegionDifference(pRegion, pOtherRegion); if(d < dBestDiff) { dBestDiff = d; nBestNeighbor = (int)j; } } GAssert(nBestNeighbor != -1 || pFineRegions->regionCount() == 1); // failed to find a neighbor pBestNeighborMap[i] = nBestNeighbor; } // Create a mapping to new regions numbers int* pNewRegionMap = new int[pFineRegions->regionCount()]; ArrayHolder<int> hNewRegionMap(pNewRegionMap); memset(pNewRegionMap, 0xff, sizeof(int) * pFineRegions->regionCount()); int nNewRegionCount = 0; for(size_t i = 0; i < pFineRegions->regionCount(); i++) { size_t nNewRegion = -1; size_t j = i; while(pNewRegionMap[j] == -1) { pNewRegionMap[j] = -2; j = pBestNeighborMap[j]; } if(pNewRegionMap[j] == -2) nNewRegion = nNewRegionCount++; else nNewRegion = pNewRegionMap[j]; j = i; while(pNewRegionMap[j] == -2) { pNewRegionMap[j] = (int)nNewRegion; j = pBestNeighborMap[j]; } } // Make the new regions for(size_t i = 0; i < pFineRegions->regionCount(); i++) { struct GRegion* pRegion = pFineRegions->m_regions[i]; size_t j = pNewRegionMap[i]; if(regionCount() <= j) { GAssert(regionCount() == j); // how'd it get two behind? addRegion(); } struct GRegion* pCoarseRegion = m_regions[j]; pCoarseRegion->m_nSumRed += pRegion->m_nSumRed; pCoarseRegion->m_nSumGreen += pRegion->m_nSumGreen; pCoarseRegion->m_nSumBlue += pRegion->m_nSumBlue; pCoarseRegion->m_nPixels += pRegion->m_nPixels; } for(size_t i = 0; i < pFineRegions->regionCount(); i++) { struct GRegion* pRegion = pFineRegions->m_regions[i]; size_t j = pNewRegionMap[i]; struct GRegionEdge* pEdge; for(pEdge = pRegion->m_pNeighbors; pEdge; pEdge = pEdge->GetNext(i)) { size_t k = pNewRegionMap[pEdge->GetOther(i)]; if(j != k) makeNeighbors(j, k); } } // Make the fine region mask unsigned int nOldRegion; int x, y; for(y = 0; y < (int)pFineRegionMask->height(); y++) { for(x = 0; x < (int)pFineRegionMask->width(); x++) { nOldRegion = pFineRegionMask->pixel(x, y); pCoarseRegionMask->setPixel(x, y, pNewRegionMap[nOldRegion]); } } }
void GImage::encodeJPEG( BinaryOutput& out) const { if (channels != 3) { // Convert to three channel GImage tmp = *this; tmp.convertToRGB(); tmp.encodeJPEG(out); return; } debugAssert(channels == 3); out.setEndian(G3D_LITTLE_ENDIAN); // Allocate and initialize a compression object jpeg_compress_struct cinfo; jpeg_error_mgr jerr; cinfo.err = jpeg_std_error(&jerr); jpeg_create_compress(&cinfo); // Specify the destination for the compressed data. // (Overestimate the size) int buffer_size = width * height * 3 + 200; JOCTET* compressed_data = (JOCTET*)System::malloc(buffer_size); jpeg_memory_dest(&cinfo, compressed_data, buffer_size); cinfo.image_width = width; cinfo.image_height = height; // # of color components per pixel cinfo.input_components = 3; // colorspace of input image cinfo.in_color_space = JCS_RGB; cinfo.input_gamma = 1.0; // Set parameters for compression, including image size & colorspace jpeg_set_defaults(&cinfo); jpeg_set_quality(&cinfo, jpegQuality, false); cinfo.smoothing_factor = 0; cinfo.optimize_coding = TRUE; // cinfo.dct_method = JDCT_FLOAT; cinfo.dct_method = JDCT_ISLOW; cinfo.jpeg_color_space = JCS_YCbCr; // Initialize the compressor jpeg_start_compress(&cinfo, TRUE); // Iterate over all scanlines from top to bottom // pointer to a single row JSAMPROW row_pointer[1]; // JSAMPLEs per row in image_buffer int row_stride = cinfo.image_width * 3; while (cinfo.next_scanline < cinfo.image_height) { row_pointer[0] = &(_byte[cinfo.next_scanline * row_stride]); jpeg_write_scanlines(&cinfo, row_pointer, 1); } // Shut down the compressor jpeg_finish_compress(&cinfo); // Figure out how big the result was. int outLength = ((mem_dest_ptr)cinfo.dest)->count; // Release the JPEG compression object jpeg_destroy_compress(&cinfo); // Copy into an appropriately sized output buffer. out.writeBytes(compressed_data, outLength); // Free the conservative buffer. System::free(compressed_data); compressed_data = NULL; }
void test_contains_and_getBounds() { bool useCompounds = false; int x0 = 350; int y0 = 300; Map<string, GObject*> shapeMap; GOval *oval = new GOval(x0, y0, 200, 100); GRoundRect *roundRect = new GRoundRect(x0, y0, 200, 100, 300); roundRect->setLineWidth(20); G3DRect *rect3d = new G3DRect(x0, y0, 200, 100, true); //rect3d->setLineWidth(5); rect3d->setFillColor("green"); rect3d->setFilled(true); GPolygon *poly = new GPolygon; poly->addVertex(0, 0); poly->addEdge(200, 100); poly->addEdge(-200, 0); poly->setLocation(x0, y0); GPolygon *cpoly = new GPolygon; cpoly->addVertex(0, 0); cpoly->addEdge(200, 100); cpoly->addEdge(0, -100); cpoly->addEdge(-200, 100); cpoly->setLocation(x0, y0); GRect *rect = new GRect(x0, y0, 200, 100); GLine *line = new GLine(x0, y0, x0 + 200, y0 + 100); GLabel *label = new GLabel("Ostromantus", x0, y0); GArc *arc = new GArc(x0, y0, 350, 350, 0, 90); //arc->setLineWidth(5); arc->setColor("#44000000"); GArc *filledArc = new GArc(x0, y0, 350, 100, 45, 225); filledArc->setFillColor("#88e0e0e0"); filledArc->setFilled(true); GCompound *comp1 = new GCompound; comp1->setLocation(x0, y0); comp1->add(new GLabel("compound", 0, 15)); GRect *bgRect1 = new GRect(0, 0); gw->add(bgRect1); bgRect1->setFillColor("#55dddddd"); bgRect1->setFilled(true); GImage *image = new GImage("homer-transparent.png"); image->setLocation(x0, y0); GCompound *comp = new GCompound; comp->setLocation(x0, y0); GRect *compRect = new GRect(20, 20, 100, 100); GOval *compOval = new GOval(90, 90, 150, 70); comp->add(compRect); comp->add(compOval); GButton *button = new GButton("Testo"); button->setSize(200, 100); button->setLocation(x0, y0); shapeMap.put("oval", oval); shapeMap.put("rounded rectangle", roundRect); shapeMap.put("3D rectangle", rect3d); shapeMap.put("polygon", poly); shapeMap.put("crazy polygon", cpoly); shapeMap.put("rectangle", rect); shapeMap.put("line", line); shapeMap.put("arc", arc); shapeMap.put("filled arc", filledArc); shapeMap.put("label", label); shapeMap.put("image", image); shapeMap.put("compound", comp); shapeMap.put("button", button); GObject *currObj; GChooser *ch = new GChooser; ch->setActionCommand("chooser"); ch->addItem("oval"); ch->addItem("rounded rectangle"); ch->addItem(("3D rectangle")); ch->addItem("polygon"); ch->addItem("crazy polygon"); ch->addItem("rectangle"); ch->addItem("line"); ch->addItem("arc"); ch->addItem("filled arc"); ch->addItem("label"); ch->addItem("image"); ch->addItem("compound"); ch->addItem("button"); ch->setSelectedItem("rectangle"); currObj = rect; GButton *endButton = new GButton("End test"); GButton *fillButton = new GButton("Auto-fill"); GButton *rotateButton = new GButton("Rotate"); GButton *scaleButton = new GButton("Scale"); GCheckBox *compCheckbox = new GCheckBox("compounds"); compCheckbox->setActionCommand("compounds"); gw->addToRegion(compCheckbox, "north"); gw->addToRegion(ch, "north"); gw->addToRegion(rotateButton, "north"); gw->addToRegion(scaleButton, "north"); gw->addToRegion(fillButton, "north"); gw->addToRegion(endButton, "north"); while (true) { GEvent e = waitForEvent(ACTION_EVENT | MOUSE_EVENT); if (!e.isValid()) continue; if (e.getEventClass() == ACTION_EVENT) { if (((GActionEvent) e).getActionCommand() == "End test") break; if (((GActionEvent) e).getActionCommand() == "compounds") { bgRect1->setVisible(compCheckbox->isSelected()); useCompounds = compCheckbox->isSelected(); } if (((GActionEvent) e).getActionCommand() == "Testo") { GPoint pt = button->getLocation(); button->setLocation(pt.getX()-button->getWidth()-10, pt.getY()); pause(1000); button->setLocation(pt); } if (((GActionEvent) e).getActionCommand() == "Auto-fill") { GRectangle bds = currObj->getBounds(); int xmin = bds.getX(); int ymin = bds.getY(); int xmax = bds.getX() + bds.getWidth(); int ymax = bds.getY() + bds.getHeight(); int dx = useCompounds ? comp1->getX(): 0; int dy = useCompounds ? comp1->getY(): 0; for (int y = ymin; y < ymax; y+=1) for (int x = xmin; x < xmax; x+=1) { if (currObj->contains(x, y)) { gw->setColor("red"); gw->fillOval(x + dx, y + dy, 1, 1); } else { gw->setColor("green"); gw->fillOval(x + dx, y + dy, 1, 1); } } } if (((GActionEvent) e).getActionCommand() == "Rotate") { currObj->rotate(45); if (useCompounds) { bgRect1->setBounds(comp1->getBounds()); } } if (((GActionEvent) e).getActionCommand() == "Scale") { currObj->scale(1.2, 0.8); if (useCompounds) { bgRect1->setBounds(comp1->getBounds()); } } if (((GActionEvent) e).getActionCommand() == "chooser") { string shape = ch->getSelectedItem(); if (useCompounds) { comp1->remove(currObj); gw->remove(comp1); } else { gw->remove(currObj); } gw->setColor("white"); gw->fillRect(0, 0, gw->getCanvasWidth(), gw->getCanvasHeight()); //drawGrid(); gw->setColor("black"); currObj = shapeMap.get(shape); if (useCompounds) { gw->add(comp1); comp1->add(currObj, 50, 50); bgRect1->setBounds(comp1->getBounds()); } else { gw->add(currObj); } gw->drawOval(currObj->getX()-2, currObj->getY()-2, 4, 4); } } else if (e.getEventType() == MOUSE_CLICKED) { double x = ((GMouseEvent) e).getX(); double y = ((GMouseEvent) e).getY(); if (currObj->contains(x, y)) { gw->setColor("red"); gw->fillOval(x, y, 1, 1); } } } }
GImage* GPlotWindow::labelAxes(int maxHorizAxisLabels, int maxVertAxisLabels, int precision, float size, unsigned int color, double angle) { int spacing = 10; int horizMargin = 200; int vertMargin = 200; GImage* pOutImage = new GImage(); pOutImage->setSize(m_pImage->width() + horizMargin, m_pImage->height() + vertMargin); pOutImage->clear(0xffffffff); GRect r(0, 0, m_pImage->width(), m_pImage->height()); pOutImage->blit(horizMargin, 0, m_pImage, &r); if(maxHorizAxisLabels > 0) { GPlotLabelSpacer spacer(m_window.x, m_window.x + m_window.w, maxHorizAxisLabels); for(int i = 0; i < spacer.count(); i++) { double pos = spacer.label(i); int x1, y1; windowToView(pos, 0, &x1, &y1); numericLabel(pOutImage, pos, horizMargin + x1, m_pImage->height() + spacing, precision, size, color, angle); } } else if(maxHorizAxisLabels == -1) { GPlotLabelSpacerLogarithmic spacer(m_window.x, m_window.x + m_window.w); while(true) { double pos; bool primary; if(!spacer.next(&pos, &primary)) break; if(primary) { double x = log(pos); int x1, y1; windowToView(x, 0, &x1, &y1); numericLabel(pOutImage, pos, horizMargin + x1, m_pImage->height() + spacing, precision, size, color, angle); } } } if(maxVertAxisLabels > 0) { GPlotLabelSpacer spacer(m_window.y, m_window.y + m_window.h, maxVertAxisLabels); for(int i = 0; i < spacer.count(); i++) { double pos = spacer.label(i); int x1, y1; windowToView(0, pos, &x1, &y1); numericLabel(pOutImage, pos, horizMargin - spacing, y1, precision, size, color, 0.0); } } else if(maxVertAxisLabels == -1) { GPlotLabelSpacerLogarithmic spacer(m_window.y, m_window.y + m_window.h); while(true) { double pos; bool primary; if(!spacer.next(&pos, &primary)) break; if(primary) { double y = log(pos); int x1, y1; windowToView(0, y, &x1, &y1); numericLabel(pOutImage, pos, horizMargin - spacing, y1, precision, size, color, 0.0); } } } return pOutImage; }