bool ImageWriterJPEG::writeMarkers()

in imagecore/formats/internal/jpeg.cpp [968:1027]


bool ImageWriterJPEG::writeMarkers()
{
	bool didWriteColorProfile = false;
	if( (m_WriteOptions & kWriteOption_CopyColorProfile) != 0 && m_SourceReader != NULL ) {
		unsigned int colorProfileSize = 0;
		uint8_t* colorProfile = m_SourceReader->getColorProfile(colorProfileSize);
		if( colorProfile != NULL && colorProfileSize > 0 ) {
			write_icc_profile(&m_JPEGCompress, colorProfile, colorProfileSize);
			didWriteColorProfile = true;
		}
	}
	if( (m_WriteOptions & kWriteOption_WriteDefaultColorProfile) != 0 && !didWriteColorProfile) {
#if IMAGECORE_WITH_LCMS
		cmsHPROFILE sRGBProfile = cmsCreate_sRGBProfile();
		if( !sRGBProfile ) {
			return false;
		}
		// First call with a null output buffer to determine output size
		unsigned int outputSize = 0;
		if( cmsSaveProfileToMem(sRGBProfile, NULL, &outputSize) ) {
			if( outputSize > 0 ) {
				// Next allocate the bytes for the profile and write into it
				cmsUInt8Number* buffer = (cmsUInt8Number*)malloc(outputSize + 1);
				if( buffer != NULL ) {
					if( cmsSaveProfileToMem(sRGBProfile, buffer, &outputSize) ) {
						write_icc_profile(&m_JPEGCompress, buffer, outputSize);
						didWriteColorProfile = true;
					}
					free(buffer);
				}
			}
		}
		cmsCloseProfile(sRGBProfile);
#endif
	}
	if( (m_WriteOptions & kWriteOption_CopyMetaData) != 0 && m_SourceReader != NULL ) {
		unsigned int exifDataSize = 0;
		uint8_t* exifData = m_SourceReader->getEXIFData(exifDataSize);
		if( exifData != NULL && exifDataSize > 0 ) {
			jpeg_write_marker(&m_JPEGCompress, EXIF_MARKER, exifData, exifDataSize);
		}
	} else {
		ExifWriter exifWriter(true);
		if ((m_WriteOptions & kWriteOption_WriteExifOrientation) != 0 && m_SourceReader != NULL && m_SourceReader->getOrientation() != kImageOrientation_Up) {
			exifWriter.putValue((uint16_t)m_SourceReader->getOrientation(), ExifCommon::kTagId::kOrientation);
		}
		if ((m_WriteOptions & kWriteOption_GeoTagData) != 0 && m_SourceReader != NULL && m_SourceReader->hasValidGeoTagData()) {
			exifWriter.putValue((uint16_t)m_SourceReader->getOrientation(), ExifCommon::kTagId::kOrientation);
			m_SourceReader->storeGeoTagData(exifWriter);
		}
		if(!exifWriter.isEmpty()) { // if anything got written to EXIF section, flush it to the jpeg writer
			uint8_t* exifData = new uint8_t[64 * 1024];
			MemoryStreamWriter exifStream(exifData, 64 * 1024, true);
			exifWriter.WriteToStream(exifStream);
			jpeg_write_marker(&m_JPEGCompress, EXIF_MARKER, exifStream.getData(), exifStream.getSize());
			delete [] exifData;
		}
	}
	return true;
}