bool CImageFileFormatChecker::isPngFile(std::wstring & fileName)
{
	eFileType = _CXIMAGE_FORMAT_UNKNOWN;
	////////////////////////////////////////////////////////////////////////////////
	NSFile::CFileBinary file;
	if (!file.OpenFile(fileName))
		return false;

	BYTE* buffer = new BYTE[MIN_SIZE_BUFFER];
	if (!buffer)
		return false;

	DWORD sizeRead = 0;
	if (!file.ReadFile(buffer, MIN_SIZE_BUFFER, sizeRead))
	{
		delete []buffer;
		return false;
	}
	file.CloseFile();
	////////////////////////////////////////////////////////////////////////////////
	
	if (isPngFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_PNG;
	}
	delete [] buffer;

	if (eFileType)return true;
	else return false;

}
Exemple #2
0
int CFontStream::CreateFromFile(const std::wstring& strFileName, BYTE* pDataUse)
{
	NSFile::CFileBinary oFile;
	if (!oFile.OpenFile(strFileName))
		return FALSE;

	m_lSize = oFile.GetFileSize();
    
    if (NULL == pDataUse)
	m_pData = new BYTE[m_lSize];
    else
    {
        m_bIsAttach = true;
        m_pData = pDataUse;
    }

	DWORD dwRead = 0;
	DWORD dwNeedRead = (DWORD)m_lSize;
	oFile.ReadFile(m_pData, dwNeedRead, dwRead);

	if (dwNeedRead != dwRead)
	{
        if (!m_bIsAttach)
		RELEASEARRAYOBJECTS(m_pData);
        
		m_lSize = 0;
		return FALSE;
	}
	
	oFile.CloseFile();
	return true;
}
Exemple #3
0
void simple_element::write(const std::wstring & RootPath)
{
	std::wstring name_ = RootPath + FILE_SEPARATOR_STR + file_name_;

	NSFile::CFileBinary file;
	if ( file.CreateFileW(name_) == true)
	{
		if (bXml)
		{
			std::string root = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>";
			file.WriteFile((BYTE*)root.c_str(), root.length());
		}
		file.WriteFile((BYTE*)content_utf8_.c_str(), content_utf8_.length());
		file.CloseFile();
	}
}
std::wstring COfficeFileFormatChecker::getDocumentID (const std::wstring & _fileName )
{
#if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN64)
    std::wstring fileName = CorrectPathW(_fileName);
#else
    std::wstring fileName = _fileName;
#endif
	std::wstring documentID;

	POLE::Storage storage(fileName.c_str());
    if (storage.open())
    {
		if ( isMS_OFFCRYPTOFormatFile(&storage, documentID) )
        {
            nFileType = AVS_OFFICESTUDIO_FILE_OTHER_MS_OFFCRYPTO;
        }
	}
	else
	{
		if ( false == isOpenOfficeFormatFile(fileName, documentID))
		{
			NSFile::CFileBinary file;
			if (!file.OpenFile(fileName))
				return documentID;
			
			unsigned char* buffer = new unsigned char[4096]; //enaf !!
			if (!buffer){file.CloseFile();return documentID;}

			DWORD dwReadBytes = 0;
			file.ReadFile(buffer, MIN_SIZE_BUFFER, dwReadBytes);
			file.CloseFile();

			if (isPdfFormatFile(buffer, (int)dwReadBytes, documentID) )
			{
				nFileType = AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_PDF;
			}
		}
	}
	sDocumentID = documentID;

	return documentID;
}
Exemple #5
0
int oneZipFile(zipFile & zf, zip_fileinfo & zi, std::wstring & file_name, std::wstring & zip_file_name, int method, int compressionLevel)
{
	int err = -1;

	NSFile::CFileBinary oFile;
	if(oFile.OpenFile(file_name))
	{
		DWORD dwSizeRead;
		BYTE* pData = new BYTE[oFile.GetFileSize()];
		if(oFile.ReadFile(pData, oFile.GetFileSize(), dwSizeRead))
		{
			std::string zipFileNameA = codepage_issue_fixToOEM(zip_file_name);
			err = zipOpenNewFileInZip( zf, zipFileNameA.c_str(), &zi, NULL, 0, NULL, 0, NULL, method, compressionLevel );
			err = zipWriteInFileInZip( zf, pData, dwSizeRead );
			err = zipCloseFileInZip( zf );
		}
		RELEASEARRAYOBJECTS(pData);
	}
	return 0;
}
Exemple #6
0
    static void CorrectImage(const wchar_t* wsFileName, BYTE*& pBuffer, int& nBufferSize, unsigned int& unWidth, unsigned int& unHeight)
    {
        pBuffer = NULL;
        nBufferSize = 0;

        CImageFileFormatChecker oChecker(wsFileName);
        if (oChecker.eFileType != _CXIMAGE_FORMAT_JPG)
            return;

        NSFile::CFileBinary oFile;
        if (!oFile.OpenFile(wsFileName))
            return;

        if (20 > oFile.GetFileSize())
            return;

        BYTE data[20];
        DWORD dwRead = 0;
        if (!oFile.ReadFile(data, 20, dwRead))
            return;

        std::string sFind((char*)data, 20);
        oFile.CloseFile();

        if (std::string::npos == sFind.find("Photoshop") && std::string::npos == sFind.find("photoshop"))
            return;

        CBgraFrame oFrame;
        if (!oFrame.OpenFile(wsFileName))
            return;

        oFrame.SetJpegQuality(85.0);
        if (!oFrame.Encode(pBuffer, nBufferSize, _CXIMAGE_FORMAT_JPG))
            return;

        if (!pBuffer || !nBufferSize)
            return;

        unWidth = (unsigned int)oFrame.get_Width();
        unHeight = (unsigned int)oFrame.get_Height();
    }
Exemple #7
0
	// CJ2kFile
	bool CJ2kFile::Open(CBgraFrame* pFrame, const std::wstring& wsSrcPath, const std::wstring& wsXmlOptions)
	{
		Image *pImage = NULL;

		DecoderParams oParameters;

		// Установим стандартные значения параметров
		ApplyDecoderOptions(&oParameters, wsXmlOptions);

		///////////////////////////////////////////////////////////////////////////////////

		NSFile::CFileBinary oFile;
		if (!oFile.OpenFile(wsSrcPath))
			return false;

		DWORD nFileSize = oFile.GetFileSize();

		int type = check_j2000_type(oFile.GetFileNative());
		oFile.CloseFile();

		bool bOpenResult = false;
		if (!bOpenResult && type == 1)
			bOpenResult = (NULL != (pImage = Jp2ToImage(wsSrcPath, &oParameters)));

		if (!bOpenResult && type == 2)
			bOpenResult = (NULL != (pImage = J2kToImage(wsSrcPath, &oParameters)));

		if (!bOpenResult && type == 3)
			bOpenResult = (NULL != (pImage = Mj2ToImage(wsSrcPath, &oParameters)));

		if (!bOpenResult && type == 4)
			bOpenResult = (NULL != (pImage = JptToImage(wsSrcPath, &oParameters)));

		if (!bOpenResult)
		{
			Image_Destroy(pImage);
			return false;
		}

		int nWidth  = pImage->pComponents[0].nWidth;
		int nHeight = pImage->pComponents[0].nHeight;
		int nBufferSize = 4 /*pImage->nCsiz*/ * nWidth * nHeight;

		if (nBufferSize < 1)
		{
			Image_Destroy(pImage);
			return false;
		}

		pFrame->put_Width(nWidth);
		pFrame->put_Height(nHeight);
		pFrame->put_Stride(4 * nWidth);

		BYTE* pData = new BYTE[nBufferSize];
		if (!pData)
		{
			Image_Destroy(pImage);
			return false;
		}

		pFrame->put_Data(pData);

		unsigned char* pBufferPtr = (unsigned char*)pData;
		long nCreatedBufferSize = nBufferSize;

		// Пишем данные в pBufferPtr
		if (pImage->nCsiz == 3 && pImage->pComponents[0].nXRsiz == pImage->pComponents[1].nXRsiz && pImage->pComponents[1].nXRsiz == pImage->pComponents[2].nXRsiz
			&& pImage->pComponents[0].nYRsiz == pImage->pComponents[1].nYRsiz && pImage->pComponents[1].nYRsiz == pImage->pComponents[2].nYRsiz
			&& pImage->pComponents[0].nPrecision == pImage->pComponents[1].nPrecision && pImage->pComponents[1].nPrecision == pImage->pComponents[2].nPrecision)
		{
			int nResW = CeilDivPow2(pImage->pComponents[0].nWidth, pImage->pComponents[0].nFactorDiv2);
			int nResH = CeilDivPow2(pImage->pComponents[0].nHeight, pImage->pComponents[0].nFactorDiv2);


			for (int nIndex = 0; nIndex < nResW * nResH; nIndex++)
			{
				unsigned char nR = pImage->pComponents[0].pData[nWidth * nResH - ((nIndex) / (nResW)+1) * nWidth + (nIndex) % (nResW)];
				unsigned char nG = pImage->pComponents[1].pData[nWidth * nResH - ((nIndex) / (nResW)+1) * nWidth + (nIndex) % (nResW)];
				unsigned char nB = pImage->pComponents[2].pData[nWidth * nResH - ((nIndex) / (nResW)+1) * nWidth + (nIndex) % (nResW)];

				pBufferPtr[0] = nB;
				pBufferPtr[1] = nG;
				pBufferPtr[2] = nR;
				pBufferPtr[3] = 255;
				pBufferPtr += 4;

			}
		}
		else if (pImage->nCsiz >= 4 && pImage->pComponents[0].nXRsiz == pImage->pComponents[1].nXRsiz && pImage->pComponents[1].nXRsiz == pImage->pComponents[2].nXRsiz && pImage->pComponents[2].nXRsiz == pImage->pComponents[3].nXRsiz
				 && pImage->pComponents[0].nYRsiz == pImage->pComponents[1].nYRsiz && pImage->pComponents[1].nYRsiz == pImage->pComponents[2].nYRsiz && pImage->pComponents[2].nYRsiz == pImage->pComponents[3].nYRsiz
				 && pImage->pComponents[0].nPrecision == pImage->pComponents[1].nPrecision && pImage->pComponents[1].nPrecision == pImage->pComponents[2].nPrecision && pImage->pComponents[2].nPrecision == pImage->pComponents[3].nPrecision)
		{
			int nResW = CeilDivPow2(pImage->pComponents[0].nWidth, pImage->pComponents[0].nFactorDiv2);
			int nResH = CeilDivPow2(pImage->pComponents[0].nHeight, pImage->pComponents[0].nFactorDiv2);


			for (int nIndex = 0; nIndex < nResW * nResH; nIndex++)
			{
				unsigned char nR = pImage->pComponents[0].pData[nWidth * nResH - ((nIndex) / (nResW)+1) * nWidth + (nIndex) % (nResW)];
				unsigned char nG = pImage->pComponents[1].pData[nWidth * nResH - ((nIndex) / (nResW)+1) * nWidth + (nIndex) % (nResW)];
				unsigned char nB = pImage->pComponents[2].pData[nWidth * nResH - ((nIndex) / (nResW)+1) * nWidth + (nIndex) % (nResW)];
				unsigned char nA = pImage->pComponents[3].pData[nWidth * nResH - ((nIndex) / (nResW)+1) * nWidth + (nIndex) % (nResW)];

				pBufferPtr[0] = nB;
				pBufferPtr[1] = nG;
				pBufferPtr[2] = nR;
				pBufferPtr[3] = nA;
				pBufferPtr += 4;

			}
		}
		else // Grayscale
		{
			int nResW = CeilDivPow2(pImage->pComponents[0].nWidth, pImage->pComponents[0].nFactorDiv2);
			int nResH = CeilDivPow2(pImage->pComponents[0].nHeight, pImage->pComponents[0].nFactorDiv2);

			for (int nIndex = 0; nIndex < nResW * nResH; nIndex++)
			{
				unsigned char nG = pImage->pComponents[0].pData[nWidth * nResH - ((nIndex) / (nResW)+1) * nWidth + (nIndex) % (nResW)];
				pBufferPtr[0] = nG;
				pBufferPtr[1] = nG;
				pBufferPtr[2] = nG;
				pBufferPtr[3] = 255;
				pBufferPtr += 4;
			}
		}

		Image_Destroy(pImage);
		return true;
	}
Exemple #8
0
	bool CJ2kFile::Open(BYTE** ppData, int& nComponentsCount, int& nWidth, int& nHeight, const std::wstring& wsSrcPath, const std::wstring& wsXmlOptions)
	{
		Image *pImage = NULL;

		DecoderParams oParameters;

		// Установим стандартные значения параметров
		ApplyDecoderOptions(&oParameters, wsXmlOptions);

		///////////////////////////////////////////////////////////////////////////////////

		NSFile::CFileBinary oFile;
		if (!oFile.OpenFile(wsSrcPath))
			return false;

		DWORD nFileSize = oFile.GetFileSize();

		int type = check_j2000_type(oFile.GetFileNative());
		oFile.CloseFile();

		bool bOpenResult = false;
		if (!bOpenResult && type == 1)
			bOpenResult = (NULL != (pImage = Jp2ToImage(wsSrcPath, &oParameters)));

		if (!bOpenResult && type == 2)
			bOpenResult = (NULL != (pImage = J2kToImage(wsSrcPath, &oParameters)));

		if (!bOpenResult && type == 3)
			bOpenResult = (NULL != (pImage = Mj2ToImage(wsSrcPath, &oParameters)));

		if (!bOpenResult && type == 4)
			bOpenResult = (NULL != (pImage = JptToImage(wsSrcPath, &oParameters)));

		if (!bOpenResult)
		{
			Image_Destroy(pImage);
			return false;
		}

		nWidth  = pImage->pComponents[0].nWidth;
		nHeight = pImage->pComponents[0].nHeight;

		int nBufferSize = pImage->nCsiz * nWidth * nHeight;
		if (nBufferSize < 1 || pImage->nCsiz <= 0)
		{
			Image_Destroy(pImage);
			return false;
		}

		*ppData = new BYTE[nBufferSize];
		if (!(*ppData))
		{
			Image_Destroy(pImage);
			return false;
		}

		unsigned char* pBufferPtr = (unsigned char*)(*ppData);
		long nCreatedBufferSize = nBufferSize;

		nComponentsCount = pImage->nCsiz;

		// Пишем данные в pBufferPtr
		for (int nComponent = 1; nComponent < nComponentsCount; nComponent++)
		{
			if (pImage->pComponents[0].nXRsiz != pImage->pComponents[nComponent].nXRsiz
				|| pImage->pComponents[0].nYRsiz != pImage->pComponents[nComponent].nYRsiz
				|| pImage->pComponents[0].nPrecision != pImage->pComponents[nComponent].nPrecision)

			{
				delete[](*ppData);
				Image_Destroy(pImage);
				return false;
			}
		}

		int nResW = CeilDivPow2(pImage->pComponents[0].nWidth, pImage->pComponents[0].nFactorDiv2);
		int nResH = CeilDivPow2(pImage->pComponents[0].nHeight, pImage->pComponents[0].nFactorDiv2);

		for (int nIndex = 0; nIndex < nResW * nResH; nIndex++)
		{
			for (int nComponent = 0; nComponent < nComponentsCount; nComponent++)
			{
				pBufferPtr[nComponent] = pImage->pComponents[nComponent].pData[nWidth * nResH - ((nIndex) / (nResW)+1) * nWidth + (nIndex) % (nResW)];
			}
			pBufferPtr += nComponentsCount;
		}

		Image_Destroy(pImage);
		return true;
	}
bool CImageFileFormatChecker::isImageFile(std::wstring& fileName)
{
	eFileType  = _CXIMAGE_FORMAT_UNKNOWN;
///////////////////////////////////////////////////////////////////////////////	
	NSFile::CFileBinary file;
	if (!file.OpenFile(fileName))
		return false;

	BYTE* buffer = new BYTE[MIN_SIZE_BUFFER];
	if (!buffer)
		return false;

	DWORD sizeRead = 0;
	if (!file.ReadFile(buffer, MIN_SIZE_BUFFER, sizeRead))
	{
		delete []buffer;
		return false;
	}
	file.CloseFile();
/////////////////////////////////////////////////////////////////////////////////
	if (isBmpFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_BMP;
	}
	if (isGifFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_GIF;
	}
	if (isPngFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_PNG;
	}
	if (isTgaFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_TGA;
	}
	if (isPcxFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_PCX;
	}	
	if (isJpgFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_JPG;
	}
	if (isEmfFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_EMF;
	}
	if (isWmfFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_WMF;
	}
	if (isTiffFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_TIF;
	}	
	if (isIcoFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_ICO;
	}
	if (isWbFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_WB;
	}	
	if (isPsdFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_PSD;
	}
	if (isRasFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_RAS;
	}	

	if (isIpodFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_UNKNOWN;
	}
	if (isJ2kFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_JP2;
	}
	if (isJp2File(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_JP2;
	}
	if (isMj2File(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_JP2;
	}
	if (isSfwFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_UNKNOWN;
	}
	if (isSvmFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_UNKNOWN;
	}
	if (isSwfFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_UNKNOWN;
	}
	if (isWbcFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_UNKNOWN;
	}	
	if (isWbzFile(buffer,sizeRead))
	{
		eFileType = _CXIMAGE_FORMAT_UNKNOWN;
	}	
///////////////////////////////////////////////////////////////////////
	if (isSvgFile(fileName))
	{
		eFileType = _CXIMAGE_FORMAT_UNKNOWN;
	}	
	if (isRawFile(fileName))
	{
		eFileType = _CXIMAGE_FORMAT_UNKNOWN;
	}
///////////////////////////////////////////////////////////////////////
	delete [] buffer;

	if (eFileType)return true;
	return false;
}
Exemple #10
0
bool CJBig2File::MemoryToJBig2(unsigned char* pBufferBGRA ,int BufferSize, int nWidth, int nHeight, std::wstring sDstFileName)
{
	// check for valid input parameters

///////////////////////////////////////////////////////////
	if ( NULL == pBufferBGRA )	return false;

	int lBufferSize   = BufferSize;
	unsigned char *pSourceBuffer = pBufferBGRA;

	PIX  *pSource = pixCreate( nWidth, nHeight, 32 );
	if ( !pSource )	return false;

	for ( int nY = 0; nY < nHeight; nY++ )
	{
		for ( int nX = 0; nX < nWidth; nX++, pSourceBuffer += 3 )//todooo сделать 3 ? 4
		{
			pixSetRGBPixel( pSource, nX, nY, pSourceBuffer[ 2 ], pSourceBuffer[ 1 ], pSourceBuffer[ 0 ] );
		}
	}


	jbig2ctx *pContext = jbig2_init( m_dTreshold, 0.5, 0, 0, ! m_bPDFMode,  m_bRefine ? 10 : -1 );

	// Пока сделаем запись одной картинки в JBig2
	// TO DO: надо будет сделать запись нескольких картинок в 1 JBig2 файл

	// Убираем ColorMap
	PIX *pPixL = NULL;
	if ( NULL == ( pPixL = pixRemoveColormap( pSource, REMOVE_CMAP_BASED_ON_SRC ) ) ) 
	{
		pixDestroy( &pSource );
		jbig2_destroy( pContext );
		return false;
	}
	pixDestroy( &pSource );

	PIX *pPixT = NULL;
	if ( pPixL->d > 1 ) 
	{
		PIX *pGray = NULL;

		if ( pPixL->d > 8 ) 
		{
			pGray = pixConvertRGBToGrayFast( pPixL );
			if ( !pGray )
			{
				pixDestroy( &pSource );
				jbig2_destroy( pContext );
				return false;
			}
		} 
		else 
		{
			pGray = pixClone( pPixL );
		}

		if (  m_bUpscale2x ) 
		{
			pPixT = pixScaleGray2xLIThresh( pGray,  m_nBwTreshold );
		} 
		else if (  m_bUpscale4x ) 
		{
			pPixT = pixScaleGray4xLIThresh( pGray,  m_nBwTreshold );
		} 
		else 
		{
			pPixT = pixThresholdToBinary( pGray,  m_nBwTreshold );
		}

		pixDestroy( &pGray );
	} 
	else 
	{
		pPixT = pixClone( pPixL );
	}

	if ( m_sOutputTreshold.length() > 0 ) 
	{
		pixWrite( m_sOutputTreshold.c_str(), pPixT, IFF_BMP );
	}

	if (  m_bSegment && pPixL->d > 1 ) 
	{
		PIX *pGraphics = segment_image( pPixT, pPixL );
		if ( pGraphics ) 
		{
			char *sFilename;
			asprintf( &sFilename, "%s.%04d.%s", m_sBaseName.c_str(), 0, ".bmp" );
			pixWrite( sFilename, pGraphics, IFF_BMP );
			free( sFilename );
		} 
		if ( !pPixT ) 
		{
			// Ничего не делаем
			return true;
		}
	}

	pixDestroy( &pPixL );

	if ( !m_bSymbolMode ) 
	{
		int nLength = 0;
		uint8_t *pBuffer = jbig2_encode_generic( pPixT, !m_bPDFMode, 0, 0, m_bDuplicateLineRemoval, &nLength );

		bool bRes = true;
        NSFile::CFileBinary file;
        if (file.CreateFileW(sDstFileName ) == true )
        {
            file.WriteFile(pBuffer, nLength);
            file.CloseFile();
			bRes = true;
        }
		else
			bRes = false;

		pixDestroy( &pPixT );
		if ( pBuffer ) free( pBuffer );
		jbig2_destroy( pContext );

		return bRes;
	}

	int nNumPages = 1;
	jbig2_add_page( pContext, pPixT );
	pixDestroy( &pPixT );

	int nLength = 0;
	uint8_t *pBuffer = jbig2_pages_complete( pContext, &nLength );
	if ( !pBuffer )
	{
		jbig2_destroy( pContext );
		return false;
	}

	if ( m_bPDFMode ) 
	{
		std::wstring sFileName = sDstFileName;//m_sBaseName + _T(".sym");

        NSFile::CFileBinary file;
        if ( file.CreateFileW(sFileName) == false)
		{
			free( pBuffer );
			jbig2_destroy( pContext );
			return false;
		}
        file.WriteFile( pBuffer, nLength );
        file.CloseFile();
	}
	free( pBuffer );

	for ( int nIndex = 0; nIndex < nNumPages; ++nIndex ) 
	{
		pBuffer = jbig2_produce_page( pContext, nIndex, -1, -1, &nLength );
		if ( m_bPDFMode ) 
		{
            std::wstring sFileName = m_sBaseName + L".0000";

            NSFile::CFileBinary file;
            if ( file.CreateFileW(sFileName) ==false)
            {
				free( pBuffer );
				jbig2_destroy( pContext );
				return false;
			}
            file.WriteFile( pBuffer, nLength );
            file.CloseFile();
		} 
		free( pBuffer );
	}

	jbig2_destroy( pContext );

	return true;
}
Exemple #11
0
bool CFontConverter::ToOTF(std::wstring sFontIn, std::wstring sFontOut, unsigned int* pSymbols, int nCount, std::wstring sNameW, long nFlag)
{
    FT_Library pLibrary = NULL;
    if ( FT_Init_FreeType( &pLibrary ) )
        return false;

    FT_Face pFace = NULL;

    NSFile::CFileBinary oFileBinary;
    if (!oFileBinary.OpenFile(sFontIn))
        return false;

    FT_Long nFileSize = (FT_Long)oFileBinary.GetFileSize();
    BYTE* pBaseAddress = new BYTE[nFileSize];
    DWORD dwRead = 0;
    oFileBinary.ReadFile(pBaseAddress, (DWORD)nFileSize, dwRead);

    FT_Open_Args oOpenArgs;
    oOpenArgs.flags = FT_OPEN_MEMORY;
    oOpenArgs.memory_base = (BYTE*)pBaseAddress;
    oOpenArgs.memory_size = nFileSize;

    NSFontConverter::CFontFileTrueType* pTTF = NSFontConverter::CFontFileTrueType::LoadFromFile( sFontIn.c_str() );
    FT_Error oerrr;
    if ( oerrr = FT_Open_Face( pLibrary, &oOpenArgs, 0, &pFace ) )
    {
        FT_Done_FreeType( pLibrary );
        RELEASEARRAYOBJECTS(pBaseAddress);
        return false;
    }

    std::string sFontFormat( FT_Get_X11_Font_Format( pFace ) );

    // Проверим флаг конвертации и исходный формат шрифта
    bool bNeedConvert = false;

    if ( nFlag == NSFontConverter::c_lFromAll ||
         ( "TrueType" == sFontFormat && nFlag & NSFontConverter::c_lFromTT ) ||
         ( "CFF" == sFontFormat && nFlag & NSFontConverter::c_lFromCFF ) ||
         ( "Type 1" == sFontFormat && nFlag & NSFontConverter::c_lFromT1 ) )
        bNeedConvert = true;

    bool bIsGids = (NSFontConverter::c_lFlagsGids & nFlag);

    if ( bNeedConvert )
    {
        if ( "CFF" == sFontFormat || "Type 1" == sFontFormat )
        {
            NSFontConverter::TCharBuffer oCFF;
            NSFontConverter::CFontFileType1C *pT1C = NULL;
            if ( "Type 1" == sFontFormat )
            {
                // Сначала сконвертируем Type1 в CFF
                NSFontConverter::CFontFileType1* pT1 = NSFontConverter::CFontFileType1::LoadFromFile( sFontIn.c_str() );
                pT1->ToCFF( &NSFontConverter::CharBufferWrite, &oCFF );
                delete pT1;

                // Конвертируем CFF в OpenTypeCFF
                pT1C = NSFontConverter::CFontFileType1C::LoadFromBuffer( oCFF.sBuffer, oCFF.nLen );
            }
            else
            {
                // FreeType отдает тип шрифта CFF, в случаях когда файл имеет тип OpenType(CFF).
                // Если так оно и есть, тогда нам с файлом ничего делать на надо.
                pT1C = NSFontConverter::CFontFileType1C::LoadFromFile( sFontIn.c_str() );
            }

            if ( pT1C )
            {
                NSFile::CFileBinary oWriteFile;
                oWriteFile.CreateFileW(sFontOut);
                pT1C->ToOpenTypeCFF( &NSFontConverter::FileWrite, oWriteFile.GetFileNative(), pFace );
                oWriteFile.CloseFile();
            }

            delete pT1C;
        }
        else if ( "TrueType" == sFontFormat && ( pSymbols != NULL || !sNameW.empty() ) )
        {
            NSFontConverter::CFontFileTrueType* pTTF = NSFontConverter::CFontFileTrueType::LoadFromFile( sFontIn.c_str() );
            if ( pTTF )
            {
                std::string sName = U_TO_UTF8(sNameW);
                unsigned char *pUseGlyfs = NULL;
                long lGlyfsCount = pFace->num_glyphs;

                if ( pSymbols )
                {
                    // Сначала составим список нужных нами GID
                    unsigned int* pUnicode = pSymbols;
                    unsigned short* pGIDs = new unsigned short[nCount];
                    int nCMapIndex = 0;

                    int nSymbolicIndex = NSFontConverter::GetSymbolicCmapIndex(pFace);

                    if (!bIsGids)
                    {
                        for ( int nIndex = 0; nIndex < nCount; nIndex++ )
                        {
                            pGIDs[nIndex] = NSFontConverter::SetCMapForCharCode( pFace, pUnicode[nIndex], &nCMapIndex  );

                            if ((pGIDs[nIndex] == 0) && (-1 != nSymbolicIndex) && (pUnicode[nIndex] < 0xF000))
                            {
                                pGIDs[nIndex] = NSFontConverter::SetCMapForCharCode( pFace, pUnicode[nIndex] + 0xF000, &nCMapIndex  );
                            }
                        }
                    }
                    else
                    {
                        for (int i = 0; i < nCount; ++i)
                            pGIDs[i] = (unsigned short)pUnicode[i];
                    }

                    pUseGlyfs = new unsigned char[lGlyfsCount];
                    ::memset( pUseGlyfs, 0x00, lGlyfsCount * sizeof(unsigned char) );
                    pUseGlyfs[0] = 1; // нулевой гид всегда записываем
                    for ( int nGID = 1; nGID < lGlyfsCount; nGID++ )
                    {
                        if ( 1 != pUseGlyfs[nGID] )
                        {
                            bool bFound = false;
                            for ( int nIndex = 0; nIndex < nCount; nIndex++ )
                            {
                                if ( nGID == pGIDs[nIndex] )
                                {
                                    bFound = true;
                                    break;
                                }
                            }

                            // Если данный символ составной (CompositeGlyf), тогда мы должны учесть все его дочерные символы (subglyfs)
                            if ( bFound && 0 == FT_Load_Glyph( pFace, nGID, FT_LOAD_NO_SCALE | FT_LOAD_NO_RECURSE ) )
                            {
                                for ( int nSubIndex = 0; nSubIndex < pFace->glyph->num_subglyphs; nSubIndex++ )
                                {
                                    FT_Int       nSubGID;
                                    FT_UInt      unFlags;
                                    FT_Int       nArg1;
                                    FT_Int       nArg2;
                                    FT_Matrix    oMatrix;
                                    FT_Get_SubGlyph_Info( pFace->glyph, nSubIndex, &nSubGID, &unFlags, &nArg1, &nArg2, &oMatrix );

                                    if ( nSubGID < lGlyfsCount )
                                        pUseGlyfs[nSubGID] = 1;
                                }
                            }

                            if ( bFound )
                                pUseGlyfs[nGID] = 1;
                        }
                    }
                }

                NSFile::CFileBinary oWriteFile;
                oWriteFile.CreateFileW(sFontOut);
                pTTF->WriteTTF( &NSFontConverter::FileWrite, oWriteFile.GetFileNative(), sName.c_str(), NULL, pUseGlyfs, lGlyfsCount );
                oWriteFile.CloseFile();
            }
            else
            {
                // error parse font
                // Просто копируем файл
                NSFile::CFileBinary::Copy(sFontIn, sFontOut);
            }
        }
    }
    else
    {
        // Просто копируем файл
        NSFile::CFileBinary::Copy(sFontIn, sFontOut);
    }

    FT_Done_Face( pFace );
    FT_Done_FreeType( pLibrary );

    RELEASEARRAYOBJECTS(pBaseAddress);

    return true;
}
Exemple #12
0
  int ZipFile( const WCHAR* inputFile, const WCHAR* outputFile, int method, int compressionLevel )
  { 
	int err = -1;

    if ( ( inputFile != NULL ) && ( outputFile != NULL ) )
    {
		NSFile::CFileBinary oFile;
		if(oFile.OpenFile(inputFile))
		{
			DWORD dwSizeRead;
			BYTE* pData = new BYTE[oFile.GetFileSize()];
			if(oFile.ReadFile(pData, oFile.GetFileSize(), dwSizeRead))
			{
				zipFile zf = zipOpenHelp(outputFile);

				zip_fileinfo zi;

				zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
					zi.tmz_date.tm_mday = zi.tmz_date.tm_mon = zi.tmz_date.tm_year = 0;
				zi.dosDate = 0;
				zi.internal_fa = 0;
				zi.external_fa = 0;

#if defined(_WIN32) || defined (_WIN64)
				SYSTEMTIME currTime;

				GetLocalTime( &currTime );

				zi.tmz_date.tm_sec = currTime.wSecond;
				zi.tmz_date.tm_min = currTime.wMinute;
				zi.tmz_date.tm_hour = currTime.wHour;
				zi.tmz_date.tm_mday = currTime.wDay;
				zi.tmz_date.tm_mon = currTime.wMonth;
				zi.tmz_date.tm_year = currTime.wYear;
#endif

				wstring inputFileName( inputFile );

				wstring::size_type pos = 0;
				static const wstring::size_type npos = -1;

				pos = inputFileName.find_last_of( L'\\' );

				wstring zipFileName;

				if ( pos != npos )
				{
					zipFileName = wstring( ( inputFileName.begin() + pos + 1 ), inputFileName.end() );
				}
				else
				{
					zipFileName = wstring( inputFileName.begin(), inputFileName.end() );
				}
				std::string zipFileNameA = codepage_issue_fixToOEM(zipFileName);
                err = zipOpenNewFileInZip( zf, zipFileNameA.c_str(), &zi, NULL, 0, NULL, 0, NULL, method, compressionLevel );
				err = zipWriteInFileInZip( zf, pData, dwSizeRead );
				err = zipCloseFileInZip( zf );
				err = zipClose( zf, NULL );
			}
			RELEASEARRAYOBJECTS(pData);
		}
	}

    return false;
  }
Exemple #13
0
  static int do_extract_currentfile( unzFile uf, const int* popt_extract_without_path, int* popt_overwrite, const char* password )
  {   	  
	char filename_inzipA[256];
	wchar_t filename_inzip[256];
    wchar_t* filename_withoutpath;
    wchar_t* p;
    int err=UNZ_OK;
	NSFile::CFileBinary oFile;
    FILE *fout=NULL;
    void* buf;
    uInt size_buf;

    unz_file_info file_info;
    uLong ratio=0;
    err = unzGetCurrentFileInfo(uf,&file_info,filename_inzipA,sizeof(filename_inzipA),NULL,0,NULL,0);

    std::wstring filenameW = codepage_issue_fixFromOEM(filename_inzipA);
	wcscpy(filename_inzip , filenameW.c_str());

    if (err!=UNZ_OK)
    {
      return err;
    }

    size_buf = WRITEBUFFERSIZE;
    buf = (void*)malloc(size_buf);
    if (buf==NULL)
    {
      return UNZ_INTERNALERROR;
    }

    p = filename_withoutpath = filename_inzip;
    while ((*p) != '\0')
    {
      if (((*p)=='/') || ((*p)=='\\'))
        filename_withoutpath = p+1;
      p++;
    }

    if ((*filename_withoutpath)=='\0')
    {
      if ((*popt_extract_without_path)==0)
      {
        mymkdir(filename_inzip);
      }
    }
    else
    {
      const wchar_t* write_filename;
      int skip=0;

      if ((*popt_extract_without_path)==0)
        write_filename = filename_inzip;
      else
        write_filename = filename_withoutpath;

      err = unzOpenCurrentFilePassword(uf,password);
      if (((*popt_overwrite)==0) && (err==UNZ_OK))
      {
        char rep=0;
		NSFile::CFileBinary oFileTemp;
		if (oFileTemp.OpenFile(write_filename))
        {
			oFileTemp.CloseFile();
        }

        if (rep == 'N')
          skip = 1;

        if (rep == 'A')
          *popt_overwrite=1;
      }

      if ((skip==0) && (err==UNZ_OK))
      {
		  if(oFile.CreateFileW(write_filename))
			 fout = oFile.GetFileNative();

        // some zipfile don't contain directory alone before file 
        if ((fout==NULL) && ((*popt_extract_without_path)==0) &&
		    (filename_withoutpath!=(wchar_t*)filename_inzip))
        {
          char c=*(filename_withoutpath-1);
          *(filename_withoutpath-1)='\0';
          makedir(write_filename);
          *(filename_withoutpath-1)=c;
		  if(oFile.CreateFileW(write_filename))
			  fout = oFile.GetFileNative();
        }
      }

      if (fout!=NULL)
      {
        do
        {
          err = unzReadCurrentFile(uf, buf, size_buf);
          if (err<0)
          {
            break;
          }
          if (err>0)
            if (fwrite(buf,err,1,fout)!=1)
            {			  
              err=UNZ_ERRNO;
              break;
            }
        }
        while (err>0);
		//close вызовется в oFile
        //if (fout)
        //  fclose(fout);

        if (err==0)
          change_file_date(write_filename,file_info.dosDate,
                           file_info.tmu_date);
      }

      if (err==UNZ_OK)
      {
        err = unzCloseCurrentFile (uf);
      }
      else
        unzCloseCurrentFile(uf); // don't lose the error 
    }

    free(buf);
    return err;
  }
	inline Global::_BlipType SaveImageToFileFromDIB(unsigned char* data, int size, const std::wstring& file_name)//without ext
	{
		Global::_BlipType result = Global::msoblipERROR;

		CBgraFrame oFrame;
		int offset = 0, biSizeImage = 0;

		__BITMAPINFOHEADER * header = (__BITMAPINFOHEADER*)data;
		if (!header) return result;

		result = Global::msoblipDIB;

		if (header->biWidth > 100000 || header->biHeight > 100000 || header->biSize != 40)
		{
			__BITMAPCOREHEADER * header_core = (__BITMAPCOREHEADER *)data;
			if (header_core->bcSize != 12)
			{
				result = Global::msoblipWMF;
			}
			else
			{
				offset = 12; //sizeof(BITMAPCOREHEADER)			
			
				oFrame.put_Height	(header_core->bcHeight );
				oFrame.put_Width	(header_core->bcWidth );
				
				int sz_bitmap = header_core->bcHeight * header_core->bcWidth * header_core->bcBitCount/ 8;
				
				//if (header_core->bcWidth % 2 != 0 && sz_bitmap < size - offset)
				//	header_core->bcWidth++;
				///???? todooo непонятно .. в biff5 нужно флипать картинку, в biff8 не ясно ( - 
				
				int stride =  -(size - offset) / header_core->bcHeight;
				oFrame.put_Stride	(stride/*header_core->bcBitCount * header_core->bcWidth /8 */);

				biSizeImage = size - offset;
				
				if (-stride >= header_core->bcWidth && header_core->bcBitCount >=24 )
				{
					result = Global::msoblipPNG;
				}
			}
		}
		else
		{
			offset = 40; //sizeof(BITMAPINFOHEADER)

			oFrame.put_Height	(header->biHeight );
			oFrame.put_Width	(header->biWidth );
			
			int sz_bitmap = header->biHeight * header->biWidth * header->biBitCount/ 8;
			
			//if (header->biWidth % 2 != 0 && sz_bitmap < size -offset)
			//	header->biWidth++;
			
			int stride = -(size - offset) / header->biHeight;

			if (-stride >= header->biWidth && header->biBitCount >= 24)
			{
				result = Global::msoblipPNG;
			}
			oFrame.put_Stride	(stride/*header->biBitCount * header->biWidth /8*/);
			
			biSizeImage = header->biSizeImage > 0 ? header->biSizeImage : (size - offset);
		}
		
//------------------------------------------------------------------------------------------

		if (result == Global::msoblipPNG)
		{
			oFrame.put_Data((unsigned char*)data + offset);
			
            if (!oFrame.SaveFile(file_name + L".png", 4/*CXIMAGE_FORMAT_PNG*/))
				result = Global::msoblipERROR;

			oFrame.put_Data(NULL);
		}
		else if (result == Global::msoblipWMF)
		{
			NSFile::CFileBinary file;
            if (file.CreateFileW(file_name + L".wmf"))
			{
				file.WriteFile((BYTE*)data, size);
				file.CloseFile();
			}
		}
		else if (biSizeImage > 0)
		{
			NSFile::CFileBinary file;
            if (file.CreateFileW(file_name + L".bmp"))
			{
                _UINT16 vtType		= 0x4D42;				file.WriteFile((BYTE*)&vtType,	2);
                _UINT32 dwLen		= biSizeImage;			file.WriteFile((BYTE*)&dwLen,	4);
                _UINT32 dwRes		= 0;					file.WriteFile((BYTE*)&dwRes,	4);
                _UINT32 dwOffset	= 2;					file.WriteFile((BYTE*)&dwOffset, 4);
			
				file.WriteFile((BYTE*)data, size);
				file.CloseFile();
			}
		}
		return result;
	}
bool COfficeFileFormatChecker::isOfficeFile(const std::wstring & _fileName)
{
#if defined(_WIN32) || defined(_WIN32_WCE) || defined(_WIN64)
    std::wstring fileName = CorrectPathW(_fileName);
#else
    std::wstring fileName = _fileName;
#endif

    //приоритет как оказывается важен
    //Metamorphic Manual for windows 28415.doc
	POLE::Storage storage(fileName.c_str());
    if (storage.open())
    {
        if ( isDocFormatFile(&storage) )
        {
			//nFileType внутри
			return true;
        }
        else if ( isXlsFormatFile(&storage) )
        {
            nFileType = AVS_OFFICESTUDIO_FILE_SPREADSHEET_XLS;
            return true;
        }
        else if ( isPptFormatFile(&storage) )
        {
#if defined FILE_FORMAT_CHECKER_WITH_MACRO
			COfficePPTFile pptFile;
			
			bMacroEnabled = true;
			long nResult = pptFile.OpenFile(fileName, L"", bMacroEnabled);
			if (nResult != S_OK)
			{
				return false;
			}         
			pptFile.CloseFile();
#endif
			nFileType = AVS_OFFICESTUDIO_FILE_PRESENTATION_PPT;
            return true;
        }
        else if ( isMS_OFFCRYPTOFormatFile(&storage, sDocumentID) )
        {
            nFileType = AVS_OFFICESTUDIO_FILE_OTHER_MS_OFFCRYPTO;
            return true;
        }
	}

    COfficeUtils OfficeUtils(NULL);
    if (OfficeUtils.IsArchive(fileName) == S_OK)
	{
             if ( isOOXFormatFile(fileName) )           return true;
        else if ( isOpenOfficeFormatFile(fileName) )    return true;
        else if ( isOnlyOfficeFormatFile(fileName) )    return true;
        else if ( isXpsFile(fileName) )                 return true;
	}
//-----------------------------------------------------------------------------------------------
    // others
    {
        NSFile::CFileBinary file;
        if (!file.OpenFile(fileName))
            return false;
		
		unsigned char* buffer = new unsigned char[4096]; //enaf !!
        if (!buffer){file.CloseFile();return false;}

        DWORD dwReadBytes = 0;
        file.ReadFile(buffer, MIN_SIZE_BUFFER, dwReadBytes);
        int sizeRead = (int)dwReadBytes;

		if ( isRtfFormatFile(buffer,sizeRead) )
		{
			nFileType = AVS_OFFICESTUDIO_FILE_DOCUMENT_RTF;
		}
		else if ( isBinaryDoctFormatFile(buffer,sizeRead) )
		{
			nFileType = AVS_OFFICESTUDIO_FILE_CANVAS_WORD;
		}
		else if ( isBinaryXlstFormatFile(buffer,sizeRead) )
		{
			nFileType = AVS_OFFICESTUDIO_FILE_CANVAS_SPREADSHEET;
		}
		else if ( isBinaryPpttFormatFile(buffer,sizeRead) )
		{
			nFileType = AVS_OFFICESTUDIO_FILE_CANVAS_PRESENTATION;
		}        
        else if (isPdfFormatFile(buffer,sizeRead) )
        {
            nFileType = AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_PDF;
        }
        else if (isDjvuFormatFile(buffer,sizeRead) )
        {
            nFileType = AVS_OFFICESTUDIO_FILE_CROSSPLATFORM_DJVU;
        }
		else if (isHtmlFormatFile(buffer,sizeRead, false))
        {
			long fileSize = file.GetFileSize();
			if (fileSize > MIN_SIZE_BUFFER)		
			{
				file.SeekFile(fileSize - MIN_SIZE_BUFFER);
				file.ReadFile(buffer, MIN_SIZE_BUFFER, dwReadBytes);
				int sizeRead = (int)dwReadBytes;
			}
			if (isHtmlFormatFile(buffer,sizeRead, true))
			{
				nFileType = AVS_OFFICESTUDIO_FILE_DOCUMENT_HTML;
			}
        }
        else if (isFB2FormatFile(buffer,sizeRead) )
        {
            nFileType = AVS_OFFICESTUDIO_FILE_DOCUMENT_FB2;
        }
		else if (isOpenOfficeFlatFormatFile(buffer,sizeRead) )
		{
			//nFileType
		}
		else if (isDocFlatFormatFile(buffer,sizeRead) )
		{
            nFileType = AVS_OFFICESTUDIO_FILE_DOCUMENT_DOC_FLAT; // without compaund container
		}

//------------------------------------------------------------------------------------------------
		file.CloseFile();

		if (buffer)delete []buffer;
		buffer = NULL;
	}
	if (nFileType != AVS_OFFICESTUDIO_FILE_UNKNOWN)return true;
//------------------------------------------------------------------------------------------------
//// by Extension

    std::wstring::size_type nExtPos = fileName.rfind(L'.');
	std::wstring sExt = L"unknown";
    
    if (nExtPos != std::wstring::npos)
        sExt = fileName.substr(nExtPos);

	std::transform(sExt.begin(), sExt.end(), sExt.begin(), tolower);

    if (0 == sExt.compare(L".mht"))
		nFileType = AVS_OFFICESTUDIO_FILE_DOCUMENT_MHT;
    else if (0 == sExt.compare(L".csv"))
		nFileType = AVS_OFFICESTUDIO_FILE_SPREADSHEET_CSV;
    else if (0 == sExt.compare(L".html") || 0 == sExt.compare(L".htm"))
		nFileType = AVS_OFFICESTUDIO_FILE_DOCUMENT_HTML;
    else if (0 == sExt.compare(L".bin")) //base64 string
		nFileType = AVS_OFFICESTUDIO_FILE_CANVAS_PDF;
    else if (0 == sExt.compare(L".doct"))//случай архива с html viewer
		nFileType = AVS_OFFICESTUDIO_FILE_TEAMLAB_DOCY;
    else //if (0 == sExt.compare(L".txt") || 0 == sExt.compare(L".xml")) //volsciv.rtf -или любой другой
        nFileType = AVS_OFFICESTUDIO_FILE_DOCUMENT_TXT;

	if (nFileType != AVS_OFFICESTUDIO_FILE_UNKNOWN) return true;

	return false;
}